Jump to content

Stopping Loop Help?


twilitegxa

Recommended Posts

I have the following code that cycles though and prints out the day of the week and stops printing after the seventh day is reached, but it keeps looping. How do I stop it from looping after 7? I thought I had it right, but it's not. Can anyone help?

 

 


<?php


$weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");


echo current($weekdays) . "<br />";
while (count($weekdays) <  {
echo next($weekdays) . "<br />";
}


?>

Link to comment
Share on other sites

count($weekdays) is not going to change. It is the number of entries in the array.

 

try using foreach instead

$weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

foreach($weekdays as $wkDay) {
  echo $wkDay . "<br />";
}

Link to comment
Share on other sites

OR

 

$weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

for($i = 0; $i < count($weekdays); $i++) {
  echo $weekdays[$i] . "<br />";
}

* Not really recommended since the count() will be executed every time the loop starts.

 

Or, if you like writing code that is on one line and difficult to read or maintain:

 

$weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

for($i = 0; $i < count($weekdays); echo $weekdays[$i++] . "<br />")  ;

* Also NOT recommended

 

by the way, if you are going to use next(), you should probably use reset() instead of current() for the first one. If you try to execute the loop a second time without a reset, the pointer will be at the end of the array and you will get an error:

 

$weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

echo reset($weekdays) . "<br />";
$i = 0;
while ($i < count($weekdays)) {
  echo next($weekdays) . "<br />";
  $i++;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.