gosulove gosulove - 1 month ago 13
PHP Question

Input <select> selected is not working correctly in PHP by comparing 2 arrays

I have

3 <select></select>


with 8 options inside (Array_1 with 8 position). All options value are the same.

What i am trying to do is that I want to make the Value in Array_2 to be the Selected value.

However, looks like my loop is not working correctly.

$array_1[]="value1";
$array_1[]="value2";
$array_1[]="value3";
$array_1[]="value4";
$array_1[]="value5";
$array_1[]="value6";
$array_1[]="value7";
$array_1[]="value8";

$array_2[]="value1";
$array_2[]="value3";
$array_2[]="value4";



for($i=0;$i<count($array_2);$i++){

echo '<select name="product_header_image[]">';

for($b=0;$b<count($array_1);$b++){
if(in_array($array_2[$i],$array_1)){
echo '<option selected VALUE="'.$array_1[$b].'" >'.$array_1[$b].'</option>';
}else{
echo '<option VALUE="'.$array_1[$b].'" >'.$array_1[$b].'</option>';
}
}

echo '</select>';
echo '<br>';

}


enter image description here

Anyone know whats wrong with my coding? what I want to achieve is the right hand side of the screenshot.

Answer

You need to replace this check:

if(in_array($array_2[$i], $array_1)) {
   ...
}

on this:

if($array_2[$i] == $array_1[$b]) {
   ...
}

Demo here