Jump to content

for loop counter


Superian

Recommended Posts

I am trying to get val =\"$i\"> to count from 1-12 instead of 0-11. How would I accomplish this?

<?php
function months() {
$month = array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$select = "<select name=\"birth_month\">\n";
$select .="<option val=\"0\">Month\n";
for ($i = 0; $i < count($month); $i++) {
  $select .= "<option val=\"".$i."\">".$month[$i]."\n"; 
}
$select .= "</option></select>";
return $select;
}

$month = months();
echo $month;
?>

Link to comment
https://forums.phpfreaks.com/topic/96633-for-loop-counter/
Share on other sites

You want to display i+1 in the value, yes?  So do that!

 

<?php
function months() {
$month = array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$select = "<select name=\"birth_month\">\n";
$select .="<option val=\"0\">Month\n";
for ($i = 0; $i < count($month); $i++) {
  $select .= "<option val=\"".($i+1)."\">".$month[$i]."\n"; 
}
$select .= "</option></select>";
return $select;
}

$month = months();
echo $month;
?>

 

It might be better to do $tmp = $i + 1, and then echo $tmp instead of ($i+1)....  Not sure.

Link to comment
https://forums.phpfreaks.com/topic/96633-for-loop-counter/#findComment-494501
Share on other sites

You want to display i+1 in the value, yes?  So do that!

 

<?php
function months() {
$month = array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$select = "<select name=\"birth_month\">\n";
$select .="<option val=\"0\">Month\n";
for ($i = 0; $i < count($month); $i++) {
  $select .= "<option val=\"".($i+1)."\">".$month[$i]."\n"; 
}
$select .= "</option></select>";
return $select;
}

$month = months();
echo $month;
?>

 

It might be better to do $tmp = $i + 1, and then echo $tmp instead of ($i+1)....  Not sure.

 

This is the output: No January

 

<select name="birth_month">

<option val="0">Month

<option val="2">February

<option val="3">March

<option val="4">April

<option val="5">May

<option val="6">June

<option val="7">July

<option val="8">August

<option val="9">September

<option val="10">October

<option val="11">November

<option val="12">December

</option></select>

Link to comment
https://forums.phpfreaks.com/topic/96633-for-loop-counter/#findComment-494505
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.