phpmultidimensional-arrayphp-5.5

PHP array_column - how to keep the keys?


I'm having issues getting the key of $items using array_column.

This is the $items array:

$items = array(
    1 => [
        "id" => 5
    ],
    3 => [
        "id" => 6
    ],
    4 => [
        "id" => 7
    ],
);
    
var_dump(array_column($items,"id"));

Result:

array (size=3)
  0 => int 5
  1 => int 6
  2 => int 7

How can I get the desired result below?

array (size=3)
  1 => int 5
  3 => int 6
  4 => int 7

Solution

  • foreach(key($parameters) as $key)
    {
    print($key);
    }
    

    You can also store that result in other variables if desired.

    And to show both keys and values try this:

    foreach ($parameters as $key => $value) {
    echo $key . ' = ' . $value . '<br>';
    }