Improve company productivity with a Business Account.Sign Up

x
?
Solved

Why is this while loop or function in general not working?

Posted on 2011-08-06
32
Medium Priority
?
1,192 Views
Last Modified: 2013-12-12
function miniDays($start){ // Function to return array of table header names with day of the week
if($start != ""){
      $days_of_the_week = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
      $key = array_search($start,$days_of_the_week);
      while($x=1;$x<8;$x++){
            if($key == 7) {$key = 0;}
            $day.$x = $days_of_the_week[$key];
            $key ++;
                       }
}
return array($day1,$day2,$day3,$day4,$day5,$day6,$day7);
}

I am trying to return an array of short weekday names. When I feed 'Wed' into the above function, I need to get back an array like this;

$week_days = miniDays['Wed']; // Should have an array of weekday names now starting with "Wed"

The above array should start like this:  "Wed", "Thu", "Fri', "Sat", "Sun", "Mon", "Tue"

But it returns nothing. Can you see any typo in my function or any mistake that is obvious? Basically you feed the function a short week name and the array returned should list all the days in the week starting with the day you fed into it.

Thanks in advance.
0
Comment
Question by:Mark Brady
  • 8
  • 8
  • 6
  • +3
31 Comments
 
LVL 3

Expert Comment

by:icarey
ID: 36323587
Hi
without testing the logic of your code
if($start != ""){
      $days_of_the_week = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
      $key = array_search($start,$days_of_the_week);
      while($x=1;$x<8;$x++){
            if($key == 7) {$key = 0;}
            $day.$x = $days_of_the_week[$key];
            $key ++;
                       }
}
usually ($x=1;$x<8;$x++) is part of a for loop
change to
      for($x=1;$x<8;$x++){
            if($key == 7) {$key = 0;}
            $day.$x = $days_of_the_week[$key];
            $key ++;
                       }
}

See if that works
0
 
LVL 84

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 400 total points
ID: 36323658
You had a few errors.  This works.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>miniDays</title>
</head>
<body>
<h1>miniDays</h1>
<?php 
error_reporting(E_ALL);

function miniDays($start){ // Function to return array of table header names with day of the week
if($start != ""){
      $days_of_the_week = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
      $key = array_search($start,$days_of_the_week);
      for($x=1;$x<8;$x++){
            if($key == 7) {$key = 0;}
            $day[$x] = $days_of_the_week[$key];
            $key ++;
            }
}
return $day;
}

//I am trying to return an array of short weekday names. When I feed 'Wed' into the above function, I need to get back an array like this;

$week_days = miniDays('Fri'); // Should have an array of weekday names now starting with "Wed"
foreach($week_days as $value) {
	echo $value." | ";
	}
 ?>
</body>
</html>

Open in new window

0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36323666
There is something wrong in your code. Use this:

<?php
error_reporting('E_ALL');
function miniDays($start){ // Function to return array of table header names with day of the week
	$arr = array();
	if($start != ""){
		$days_of_the_week = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
		$key = array_search($start,$days_of_the_week);
		echo "key is $key<br />";
		for($x=0;$x<7;$x++){
			if($key == 7) {$key = 0;}
			 array_push($arr, $days_of_the_week[$key]);
			 echo "day is $days_of_the_week[$key]<br />";
			 $key ++;
		}
	}
	return $arr;
}
echo "<pre>";
var_dump(miniDays(Wed));
?>

Open in new window




I suggest to read this book to learn php: http://www.sitepoint.com/books/phpmysql4/

Cheers
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 36323681
@marqusG, E_ALL is a defined integer constant and should not be quoted as a string.
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 36323682
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36323692
Oooops, yes of course. I just wake up :-)
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 36323709
Well, good cause I'm about to go to sleep!
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36323745
Lol: have a good night
0
 
LVL 7

Assisted Solution

by:Sandeep Kothari
Sandeep Kothari earned 400 total points
ID: 36323795
you had done 3 mistakes in your code...

mistake 1
use while instead of for
 while($x=1;$x<8;$x++){ // INCORRECT
 for($x=1;$x<8;$x++){ // CORRECT

Open in new window


mistake 2
 $day.$x = $days_of_the_week[$key]; // INCORRECT
$day[] // CORRECT

Open in new window


mistake 3
$week_days = miniDays['Wed']; // SQUARE BRACKETS - INCORRCT
$week_days = miniDays[(Wed'); // ROUND BRACKETS - CORRECT

Open in new window


hence this function is not working ...

0
 
LVL 7

Expert Comment

by:Sandeep Kothari
ID: 36323798
Some syntax error in mistake 3...
so let me repeat it here..
mistake 3
$week_days = miniDays['Wed']; // SQUARE BRACKETS - INCORRCT
$week_days = miniDays('Wed'); // ROUND BRACKETS - CORRECT

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36324229
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 36324242
Thanks icarey but the "for() does not work as well. Using While does the same thing as the "for" loop except the "while" loop may miss the very first value as it needs to be set first. Either way, I could or should be able to use either one for this function. thanks for your help though...
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 36324266
kshna:  Thanks I will try making those changes and see what happens. The 3rd mistake was a typo in this question. Of course I call the function the proper way in my actual script  "using ( )".

Thanks Ray but there is a small logic problem with the function I wrote and
I was getting very tired (you know how that gets) so could not see the problem. I write functions every day off the top of my head and they all work fine except this one and I could not put my finger on the problem. I'm going to look at kshna's suggestions.

MarqusG:

Why would I want to do any "echo" statements in this function? What I needed was someone to point out why my function does not work. I also do not need to get a book and learn PHP. I am a full time php developer for years and am just having a bad day. Thanks though :)

0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1200 total points
ID: 36324269
Here is how I would probably package that function.
http://www.laprbass.com/RAY_temp_elvin66.php

Best to all, ~Ray
<?php // RAY_temp_elvin66.php
error_reporting(E_ALL);
echo "<pre>";
date_default_timezone_set('America/New_York');



// FUNCTION TO RETURN DAYS OF THE WEEK FROM AN INPUT DAY OR DATE
function miniDays($t)
{
    // $t TRANSFORMATION IS OPTIONAL IF YOU WANT TO LET THE INPUT TO BE ANY DATETIME STRING
    $t = date('D', strtotime($t));
    $d = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
    return array_slice($d, array_search($t, $d), 7);
}



// TEST THE FUNCTION
echo "VALID" . PHP_EOL;
print_r(minidays('Sun'));
print_r(minidays('Mon'));
print_r(minidays('Tue'));
print_r(minidays('Wed'));
print_r(minidays('Thu'));
print_r(minidays('Fri'));
print_r(minidays('Sat'));

echo "BOGUS" . PHP_EOL;
print_r(minidays('bogus'));

Open in new window

0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36324283
"Thanks icarey but the "for() does not work as well"

This simply isn't true: your while loop just doesn't work at all because it's incorrect;

for syntax is

                     for ($x = 0; $x < 7; $x++) {
                        do some stuff
                     }

while syntax is
           
                    $x = 0;  
                    while ($x < 7) {
                       do some stuff
                    }

Both DaveBalwin and mine solutions work fine using for and they doesn't miss anything. I say this because I've tested them and I'm sure about the result. Please, take a moment to test our solutions and you'll see they work as you wish.

Cheers

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36324285
Hmm... Now that I look at it again, I think I over-coded it.  You do not need that last 'Sat' position.  Oh, well...
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36324290
Sorry, but when I saw a while loop written that way I thought you were a novice: It was not my intention to offend you :-). About my echoes it was only for testin: I simply forgot to delete them.

Regards

Oh, sorry if I explained while and for loops: I didn't know you were a php developer...
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36324335
@elvin66: Didn't like my solution at ID:36324269, eh?  

Probably too simple ;-)

Best regards, ~Ray
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 36324398
MarqusG: I think you missread my reply. What I meant to say (re-worded) using "for($i=0; etc... ALSO does not work. I meant that changing the loop to a for loop did not solve my problem.
The problem turned out to be on this line:

$day.$x = $days_of_the_week[$key];

I was trying to create 7 variables like this:

$day1;
$day2;
$day3;  etc and they would each hold the 3 lettered short version of the "day". Sorry I wasn't clear on my response. I do know how loops work - I work full time in the industry.
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 36324407
Sorry Ray, you posted that solution AFTER I made my post and after I accepted or at least that's what I saw on my browser. I posted at 11:43 and you at 11:44pm. After I posted I scrolled up to accept another solution that helped me fix my function. Unfortunately I did not scroll down to see your post for some reason. First time I've actually missed a post. Sorry Ray. I was actually waiting to see what you had to say to !
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36324570
Hey, elvin66, No Problem.  I didn't have the benefit of being up all night to work on it.  And I am a very lazy programmer anyway, so I would not hurry without testing the solutions.  It takes me longer that way, but I find that in the long run, good testing saves me time.

When you post a question you might want to give yourself a time budget of 24 hours to get answers.  One rotation around the world is usually enough to get several sets of eyes on the question.  It was 11:44 for you, but it was 7:44am on Sunday for me, and I was just checking in before church.  When I saw the question I had this strange feeling that something was overly complicated and the looping mechanism was not necessary, but it took me a few moments to check the syntax and make up the test cases to prove the theory.

 ;-)

On to the next, ~Ray
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 36325337
Interesting.  Your accepted solution incorporates what I posted at ID:36323658, the second post, way before your solution.  Did you not see what I did?
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 36325983
Hi Dave. No I obviously did not read ANYONES post properly and skimmed over them as I was tired. I have NEVER had such a mess in all my years as an expert myself. I think if you look at my profile you will see that I am no beginner and I know how the system works ok. I want to apologize to
Ray and Dave for jumping the gun here.

I have re-read ALL the answers and I stick by my previous comments except I will be changing my choice and asking for a split. I have asked for attention on this question as the correct way forward is to have the points split as follows:

Acepted 300 points 36324269 (Ray)  Definitely an excellent solution !
Split        100 points 36323658 (Dave) and
Split        100 points 36323795 (Kshna)

Sometimes when you have been coding for days on end and your style of coding is writing pages and pages of code without testing it because you know what you are doing (that's how I code usually) you get stuck on a problem. It may be a logic problem or it may be a coding problem. In my case, I had a logic problem of how to code a function (the best method). When you have been working on it for a couple of hours and you realise you are wasting precious time you call for help which is what I did.

Unfortunately, sometimes we get tunnel vision and we are really searching/hoping for an answer that closely resembles what we have done. When this happens, it can cause us to skim over solutions that are indeed correct but written entirely differently (different logic). In this case, this is what happened.

Once again, sorry. I will get this fixed up and thank you all. Have a nice day.
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 36326025
Ok, that's cool.  I can't code the way you do, I have to stop and test frequently.  That's to prevent me from having to go back run the tests later!  If I have something that will be a large 'switch', I will normally code each 'case', one at a time, and test it.  It probably makes for simpler code but that's how I like it.  I hate it when I go back to something and have trouble figuring out what I did.
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 36326031
I think Ray uses Chuck Norris coding... he thinks about it and when he types, it wouldn't dare come out wrong.
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 36326076
Haha yeah that sounds like Ray!
0
 
LVL 20

Author Closing Comment

by:Mark Brady
ID: 36326458
Sorry for the confusion. Now I have it right!
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 36326502
Cool, thanks for the points.
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 36327109
@elvin66 only a last comment to avoiud you think I completely stupid. If you had read my comment ID 36323666 more carefully, you would had saw that I not only changed while with a for loop, but I also introduced an array $arr (DaveBaldwin used $day instead: I used $arr declaring it only to make it evident - that has not been useful). If you had tested my code or DaveBaldwin code before than mine, you would had noticed that they worked doing exactly what you wished. Maybe you are a so great coder to not need to test your code, but this case proves how testing is a useful activity and not a time wasting task.

Best regards.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36328851
@elvin66, thanks for the points.  I used your question to add Practical Application #10 to this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

Best to all, over and out, ~Ray
0
 
LVL 20

Author Comment

by:Mark Brady
ID: 36332475
Hey there is some very helpful information in that article Ray. Well done and glad my question could help :)
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

585 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question