peace_love
peace_love

Reputation: 6471

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>

Upvotes: 1

Views: 173

Answers (3)

mickmackusa
mickmackusa

Reputation: 47990

Your array data is perfectly prepared for iterated calls of vsprintf() to elegantly and clearly populate the option tag strings. This eliminates messy, hard-to-maintain code that leverages concatenation and/or interpolation to form strings with multiple variables.

I absolutely would implode these strings with a newline character in a professional script. There is nothing unprofessional about using a foreach() loop to make these vsprintf() calls either.

Code: (Demo)

echo implode(
         "\n",
         array_map(
             fn($row) => vsprintf(
                 '<option "%d">%s %s</option>',
                 $row
             ),
             $array
         )
     );

For more explicit control of the elements used in the option tag string, use sprintf() and hardcode the element keys. (Demo)

echo implode(
         "\n",
         array_map(
             fn($row) => sprintf(
                 '<option "%d">%s %s</option>',
                 $row['id'],
                 $row['name'],
                 $row['firstname']
             ),
             $array
         )
     );

Output (from either snippet):

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

Upvotes: 0

Constantin Galbenu
Constantin Galbenu

Reputation: 17683

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>";

Upvotes: 1

hassan
hassan

Reputation: 8308

using implode is not the prober way in this context:

using foreach:

echo '<select>';
foreach ($array as $key => $value) {
    echo '<option value ="'.$value['id'].'">'.$value['firstname'].' '.$value['name'].'</option>';
}
echo '</select>';

Upvotes: 2

Related Questions