Jump to content

increment with a twist


unixbro

Recommended Posts

<?php

$i = 1;

while ($i <= 100) { //Execute the statements below if this is TRUE

  echo $i; //Print the value of $i

  echo "<OPTION>$i</OPTION>"; //print a space

  $i++;  //Increment value of $i by 1

  }

?>

 

the above is supposed to print a select box with options from 1 to 100

 

My problem is when it reaches 50 I want it to print <OPTION selected>50</OPTION>

 

all other variables I would like to keep as <OPTION>$i</OPTION> where $i will be 1 to 100

 

not sure if this makes sense.

 

Thanks in advance

Link to comment
https://forums.phpfreaks.com/topic/94705-increment-with-a-twist/
Share on other sites

I am not a php expert but this should be it shouldnt it?

 

<?php
$i = 1;
while ($i <= 100) { //Execute the statements below if this is TRUE
echo $i; //Print the value of $i
if ($i == 50) {
	echo "<OPTION selected>50</OPTION>";
} else {
	echo "<OPTION>$i</OPTION>"; //print a space
}
   $i++;  //Increment value of $i by 1
   }
?>

Another way to crack that nut.

 

<?php
// In case something in your code changes this
$to_select = 50;
for ($i = 1; $i <= 100; $i++) {
  echo $i; //Print the value of $i
  $selected = $i == $to_select ? ' selected="selected"' : '';
  echo "<option{$selected}>{$i}</option>";
}
?>

Not sure what you are meaning in your last reply, but I just tested this:

 

<?php
echo "<select name=\"test\">";
$i = 1;
while ($i <= 100) { //Execute the statements below if this is TRUE
echo "The value is: ".$i."<br />"; //Print the value of $i
if ($i == 50) {
	echo "<OPTION selected>50</OPTION>";
} else {
	echo "<OPTION>$i</OPTION>"; //print a space
}
   $i++;  //Increment value of $i by 1
   }
   echo "</select>";
?>

 

And it worked perfectly, obviously it does not do the "The value is X" line as it is in the middle of a select box, so has no place to echo that line to, but it did create a select box with 100 options and the 50 as the default selected option.

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.