Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1121
  • Last Modified:

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

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
Mark Brady
Asked:
Mark Brady
  • 8
  • 8
  • 6
  • +3
3 Solutions
 
icareyCommented:
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
 
Dave BaldwinFixer of ProblemsCommented:
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
 
Marco GasiFreelancerCommented:
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
Dave BaldwinFixer of ProblemsCommented:
@marqusG, E_ALL is a defined integer constant and should not be quoted as a string.
0
 
Dave BaldwinFixer of ProblemsCommented:
0
 
Marco GasiFreelancerCommented:
Oooops, yes of course. I just wake up :-)
0
 
Dave BaldwinFixer of ProblemsCommented:
Well, good cause I'm about to go to sleep!
0
 
Marco GasiFreelancerCommented:
Lol: have a good night
0
 
Sandeep KothariProject LeadCommented:
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
 
Sandeep KothariProject LeadCommented:
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
 
Ray PaseurCommented:
0
 
Mark BradyAuthor Commented:
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
 
Mark BradyAuthor Commented:
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
 
Ray PaseurCommented:
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
 
Marco GasiFreelancerCommented:
"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
 
Ray PaseurCommented:
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
 
Marco GasiFreelancerCommented:
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
 
Ray PaseurCommented:
@elvin66: Didn't like my solution at ID:36324269, eh?  

Probably too simple ;-)

Best regards, ~Ray
0
 
Mark BradyAuthor Commented:
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
 
Mark BradyAuthor Commented:
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
 
Ray PaseurCommented:
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
 
Dave BaldwinFixer of ProblemsCommented:
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
 
Mark BradyAuthor Commented:
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
 
Dave BaldwinFixer of ProblemsCommented:
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
 
Dave BaldwinFixer of ProblemsCommented:
I think Ray uses Chuck Norris coding... he thinks about it and when he types, it wouldn't dare come out wrong.
0
 
Mark BradyAuthor Commented:
Haha yeah that sounds like Ray!
0
 
Mark BradyAuthor Commented:
Sorry for the confusion. Now I have it right!
0
 
Dave BaldwinFixer of ProblemsCommented:
Cool, thanks for the points.
0
 
Marco GasiFreelancerCommented:
@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
 
Ray PaseurCommented:
@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
 
Mark BradyAuthor Commented:
Hey there is some very helpful information in that article Ray. Well done and glad my question could help :)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 8
  • 8
  • 6
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now