Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A more condensed way of doing the following loop?

I have the following for-loop. It uses the values 0-6 form monday-sunday respectively.

Is there a more condensed way to do this? As opposed to listing out the if ($i=="day")

// $i = 0 is monday... $i = 6 is Sunday
for($i=0;$i<7;$i++){

    if ($i==0)
        echo ' <input name="repeat_on_week[]" type="checkbox" value="0"  /> Monday';
    if ($i==1)
        echo ' <input name="repeat_on_week[]" type="checkbox" value="1" /> Tuesday';
    if ($i==2)
        echo ' <input name="repeat_on_week[]" type="checkbox" value="2" /> Wednesday';
    if ($i==3)
       echo ' <input name="repeat_on_week[]" type="checkbox" value="3" /> Thursday';
    if ($i==4)
       echo ' <input name="repeat_on_week[]" type="checkbox" value="4" /> Friday';
    if ($i==5)
        echo ' <input name="repeat_on_week[]" type="checkbox" value="5" /> Saturday';
    if ($i==6)
        echo ' <input name="repeat_on_week[]" type="checkbox" value="6" /> Sunday';

}
like image 347
kylex Avatar asked Jun 10 '10 18:06

kylex


2 Answers

How about:

$days = array('Monday', 
              'Tuesday', 
              'Wednesday', 
              'Thursday', 
              'Friday', 
              'Saturday', 
              'Sunday'
        );

for($i = 0; $i < 7; $i++) {
   echo '<input name = "repeat_on_week[]" type = "checkbox" value = "' . $i . '" />' . $days[$i];
}

Or use a foreach; it's easier on the eyes and you don't have to figure out the length of the array:

for($days as $i => $day) {
   echo "<input name = \"repeat_on_week[]\" type = \"checkbox\" value = \"$i\" /> $day";
}

It's a good sign that you thought "there has to be a better way to do this!". It means that you're moving in the right direction*. But I would also suggest brushing up on the concepts of arrays and when it is good to use them.

*A good programmer always thinks his or her code sucks, which is another way of saying that a good programmer is always trying to improve himself or herself, which is also another way of saying that a good programmer is humble.

like image 81
Vivin Paliath Avatar answered Oct 20 '22 06:10

Vivin Paliath


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

for($i=0; $i<7; $i++){
    echo ' <input name="repeat_on_week[]" type="checkbox" value="' . $i . '"  /> ' . $days[$i];
}
like image 43
Richard Fearn Avatar answered Oct 20 '22 06:10

Richard Fearn