PHP with HTML - Place an array inside a select html

Asked

Viewed 2,335 times

1

Hello, I am beginner and I have the following question, I have an array, where one of the parameters comes from the bank, where the number 5 is, comes from the bank.

$inicio = 1;
$ultimo = 5; //esse valor vem do banco.
$arr = range($inicio, $ultimo);
print_r($arr);

with the above code returns an array of 1 to the number registered in the database, in this example the 5.

following the example I would like to put this array in a select html, from 1 to 5 in case I tried with for but did not succeed, can someone give me a light? thank you

2 answers

0


You can use the command foreach or the for as follows:

<select>
<?php
    foreach ( $arr as $k => $v ) {
        echo "<option value=\"" . $k . "\">" . $v . "</option>";
    }
?>
</select>

The variable $k contains the key that indexes the array, which can be either a numeric key or an associative key (a string); $v contains the value of the element in the position $arr[$k].

That is to say:

$arr[$k] === $v // true
  • 1

    Only one detail, in this case the value ($k) would always be -1 compared to the one displayed in the option ($v), since one part of 0 and the other of 1.

  • It worked perfectly Vinicius, thank you very much, I understood well the use of foreach.

0

You can use this:

<?
$inicio = 1; 
$ultimo = 5; //esse valor vem do banco.

$arr = range($inicio, $ultimo);

print_r($arr);
?>
<select name="n">
<?
foreach($arr as $n){ 
?>

<option name = "n"value="<? echo $n ?>"><? echo $n ?></option>

<? 
} 
?>
</select>

This will display a SELECT in HTML, with the options set in $n being the same as $arr.

For each $n will display an OPTION within a SELECT.

  • Also worked Inkeliz, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.