Skip to content
Advertisement

Populate option tags using three values from each row of a multidimensional array

I want to populate option tags from my array:

$array = [
    [
        "id" => "64",
        "name" => "Freddy",
        "firstname" => "Lang"
    ],
    [
        "id" => "77",
        "name" => "Samual",
        "firstname" => "Johnson"
    ]
];

I tried with:

$id = array_column($array, 'id');
$firstname = array_column($array, 'firstname');
$name = array_column($array, 'name');
echo "<select>";
  echo implode('<option value ="'.$id.'"'>'.$firstname.' '.$name.'</option>); 
echo "</select>";

But I get a blank page as result.

I expect:

<option "64">Freddy Lang</option>
<option "77">Samual Johnson</option>

Advertisement

Answer

You could use array_map to transform the input array into the html code for a <option> then implode all, using only one statement:

echo "<select>" . implode('', array_map(function($row) { 
     return '<option value="'.$row['id'].'">'. $row['firstname'] .' '. $row['name'].'</option>';
 }, $array )) . "</select>";
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement