0

I want to get the values by key from my array:

array(2) {
  [0]=>
  array(14) {
    ["id"]=>
    string(2) "64"
    ["name"]=>
    string(9) "Freddy"
    ["firstname"]=>
    string(7) "Lang"
  }
  [1]=>
  array(14) {
    ["id"]=>
    string(2) "77"
    ["name"]=>
    string(6) "Samual"
    ["firstname"]=>
    string(5) "Johnson"

  }
}

$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.

peace_love
  • 5,799
  • 9
  • 52
  • 132

2 Answers2

2

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>';
hassan
  • 7,484
  • 2
  • 23
  • 33
  • Ok, I use foreach if this is the best way :) – peace_love Mar 21 '17 at 11:28
  • I don't agree with your statement: `using implode is not the proper way in this context:`; `implode` is fine if used the right way. Anyway, your solution is OK :) – Constantin Galbenu Mar 21 '17 at 11:29
  • @ConstantinGALBENU greeting, as i said it is not the prober way in **this context**, and don't meant that is implode can not do task like this -*even as a work-around*- – hassan Mar 21 '17 at 12:01
  • for example, your solution is pretty cool, but if the `id` element is was the array key ? array map it self does not return the array key, and you will need to use array_walk for example, while you can easily handle this using foreach – hassan Mar 21 '17 at 12:05
1

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>";
Constantin Galbenu
  • 15,934
  • 3
  • 28
  • 43