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';
}
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.
$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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With