Reputation: 93
I'm creating this school project that has this <select>
tag where if the <option>
value is equal to a certain number, it will not show, display or print.
Example: if the set of numbers is 1,2,4,5,9 then only the <option>
tag that has a value of 3,6,7,8,10,11,12 will show.
<select name="">
<?php
$set_of_numbers = "1,2,4,5,9";
for($i=0; $i<=12; $i++) {
if($i != $set_of_numbers) {
echo '<option value='.$i.'>'.$i.'</option>';
}
}
?>
</select>
Upvotes: 1
Views: 2166
Reputation: 23958
You can use array_diff to only get the numbers that is not in the list.
$set_of_numbers = "1,2,4,5,9";
$numbers = explode(",", $set_of_numbers);
$range = range(1,12);
$numbers_to_output = array_diff($range, $numbers);
// [3,6,7,8,10,11,12]
foreach($numbers_to_output as $n){
echo '<option value='.$n.'>'.$n.'</option>';
}
This way you only loop the values that you want to echo.
Other methods will loop all values and need to compare each value to your list of numbers.
The code can be condensed in to:
foreach(array_diff(range(1,12), explode(",",$set_of_numbers)) as $n){
echo '<option value='.$n.'>'.$n.'</option>';
}
Upvotes: 1
Reputation: 436
You have to be able check the numbers in the set programmatically, like so:
<select name="">
<?php
$set_of_numbers = [1, 2, 4, 5, 9];
for ($i = 1; $i <= 12; $i++) {
if (!in_array($i, $set_of_numbers)) {
echo '<option value='.$i.'>'.$i.'</option>';
}
}
?>
</select>
If your set of numbers
is and can only be a string
, then you would probably go with something like this:
$set_of_numbers = "1,2,4,5,9";
$set_of_numbers = explode(',', $set_of_numbers); // This makes an array of the numbers (note, that the numbers will be STILL stored as strings)
If you want to be able to compare the numbers as integers, the solution would be:
$set_of_numbers = "1,2,4,5,9";
$set_of_numbers = json_decode('[' . $set_of_numbers . ']'); // This creates a valid JSON that can be decoded and all of the numbers WILL be stored as integers
Hope, you've got this :)
Upvotes: 3
Reputation: 182
Do the following changes to your code, this should work.
$set_of_numbers = array(1,2,4,5,9)
...
if (!in_array($i, $set_of_numbers))
Upvotes: 3