Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 960
Run Avatar asked Nov 29 '14 16:11

Run


People also ask

How do I get keys in PHP?

PHP: array_keys() function The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

Can PHP arrays have duplicate keys?

Arrays contains unique key. Hence if u are having multiple value for a single key, use a nested / multi-dimensional array. =) thats the best you got.

Is key exist in array PHP?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.


1 Answers

See if this could help

array_filter(array_combine(array_keys($items), array_column($items, 'id')));
like image 88
Ashish Choudhary Avatar answered Sep 28 '22 00:09

Ashish Choudhary