Multi-select to Array
17,210
Solution 1
//this should be $_GET['colors'][0]
echo $_GET[$colors[0]]," is your first color.";
//the , is wrong, you need to use . (point)
echo $_GET[$colors[0]]," is your first color.";
//Delete the $
if(isset($_GET["$colors"])){
//it's $_GET['colors']
for($colornum=0; $colornum<count($_GET["$colors"]); $colornum++){
//Here you need to use $_GET['colors'][$colornum]
echo $_GET[$colors[$colornum]]," ";
}
To output an array use print_r() instead of echo:
print_r($_GET["colors"]);
Solution 2
Try this,
<form method="POST">
<select multiple="yes" name="colors[]">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option>
</select>
</form>
<?php
$selected_colors = $_POST['colors'];
foreach($selected_colors AS $key=>$values)
{
echo $values.",";
}
?>
Solution 3
The $_GET is presented as an array at this point and you are not referencing the key correctly, it is a string and not a variable see below
<?php
$number=10;
echo "hello";
if (isset($_GET["name"])){
echo " ".$_GET["name"];
echo "<br />";
}
echo count($_GET["colors"]), " ", $_GET["colors"], "<br />";
echo $_GET["colors"][0]," is your first color.";
if(isset($_GET["colors"])){
echo "You must like ";
for($colornum=0;$colornum<count($_GET["colors"]);$colornum++){
echo $_GET["colors"][$colornum]," ";
}
}
?>
Solution 4
Why are you using $colors
variable like $_GET[$colors[0]]
. This is string not a variable. Instead of this use like this :
$_GET['colors'][0]
Author by
jimbo1qaz
Updated on June 04, 2022Comments
-
jimbo1qaz almost 2 years
<!DOCTYPE html> <html> <head> <title>My Form</title> <meta charset="UTF-8" /> </head> <body> <form method="get"> <div>Name <input name="name" size="15" type="text" /> </div> <select multiple="yes" name="colors[]"> <option> 1 </option> <option> 2 </option> <option> 3 </option> <option> 4 </option> <option> 5 </option> </select> </form> <?php $number=10; echo "hello"; if (isset($_GET["name"])){ echo " ".$_GET["name"]; echo "<br />"; } echo count($_GET["colors"]), " ", $_GET["colors"], "<br />"; echo $_GET[$colors[0]]," is your first color."; if(isset($_GET["$colors"])){ echo "You must like "; for($colornum=0;$colornum<count($_GET["$colors"]);$colornum++){ echo $_GET[$colors[$colornum]]," "; } } ?> </body> </html>
Why doesn't this work? The select multiple doesn't output right in the array, or possible Has a lot of debugging stuff that doesn't help my understanding much. I get undefined index and variable errors. Here's my output after selecting options 1-3:
Name hello jimbo1qaz 3 Array Notice: Undefined variable: colors in E:\xampp\htdocs\myform.php on line 28 Notice: Undefined index: in E:\xampp\htdocs\myform.php on line 28 is your first color. Notice: Undefined variable: colors in E:\xampp\htdocs\myform.php on line 29