21

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
Typewar
  • 825
  • 1
  • 13
  • 28
Run
  • 54,938
  • 169
  • 450
  • 748

10 Answers10

36

See if this could help

array_filter(array_combine(array_keys($items), array_column($items, 'id')));
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Ashish Choudhary
  • 2,004
  • 1
  • 18
  • 26
  • 2
    Will this work even if some of the items don't have an 'id'? – John Franklin Sep 05 '15 at 18:49
  • 1
    No, This is not a generic code. It will work for the question asked above though. – Ashish Choudhary Sep 17 '15 at 16:45
  • Thanks for this answer. Why do you need array_filter() to make this work though? – Zevi Sternlicht Sep 04 '18 at 20:37
  • 1
    @ZeviSternlicht `array_filter()` eliminates the `empty strings`, `null` and `false` values, thereby giving you a clean array. If you want you can remove `array_filter()` and have the array with null and empty values as well. – Ashish Choudhary Sep 06 '18 at 06:31
  • thanks, although array_column could have a switch parameter for such behavior like you posted – FantomX1 Aug 28 '19 at 09:02
  • @JohnFranklin No, this won't work if some items don't have 'id'. See https://3v4l.org/im2gZ. You get "Fatal error: Uncaught ValueError: array_combine(): Argument #1 ($keys) and argument #2 ($values) must have the same number of elements". – donquixote Sep 07 '21 at 23:51
10

I think this is the fastest way to keep keys without loops and iterations

array_diff(array_combine(array_keys($items), array_column($items, 'id')), [null])
danronmoon
  • 3,814
  • 5
  • 34
  • 56
Igor Tashlykov
  • 101
  • 1
  • 4
5

Looking for the same solution and combine some tricks, I created this:

$userdb=Array
(
    "test1" => array
    (
        'uid' => '100',
        'name' => 'Sandra Shush',
        'url' => 'urlof100'
    ),
    "test2" => array
    (
        'uid' => '5465',
        'name' => 'Stefanie Mcmohn',
        'pic_square' => 'urlof100'
    ),
    "test3" => array
    (
        'uid' => '40489',
        'name' => 'Michael',
        'pic_square' => 'urlof40489'
    )
);

echo $key = array_search(
    40489,
    array_filter(
        array_combine(
            array_keys($userdb),
            array_column(
                $userdb, 'uid'
            )
        )
    )
);

Result is 'test3'.

Work in array numbers or named arrays.

Bruno Rigolon
  • 439
  • 6
  • 5
5

The simplest and the most performant way is probably using

array_combine(array_keys($data), array_column($data, 0));
lewis4u
  • 14,256
  • 18
  • 107
  • 148
kiler129
  • 1,063
  • 2
  • 11
  • 21
  • 1
    I noticed that array_column doesn't return a value if the column doesn't exist. So this may cause trouble where you have more array keys returned than array columns so only do it if you know it will always exist for all indexes – Corby Jurgens Dec 16 '21 at 07:05
4

Another alternative is to use array_map

$result = array_map(function($item) {return $item['id'];}, $items);

ajp
  • 51
  • 2
  • 1
    This is a solution for the example, but no valid solution to the problem. If you have an array with a "subarray" which does not contain a key-value pair with the key id, this pair would still be in the result, as with array_column it would not. – Flummiboy Feb 15 '17 at 09:19
  • There is nothing wrong with how this answer provides a concise solution for the sample data provided in the question. – mickmackusa Jul 30 '22 at 03:14
3

I wrote a simple function array_column_keys that has the same parameters as array_column.

/**
 * Return the values from a single column in the input array by keeping the key
 *
 * @param array $array     A multi-dimensional array (record set) from which to pull a column of values.
 * @param mixed $column    The column of values to return. This value may be the integer key of the column you wish to retrieve, or it may be the string key name for an associative array. It may also be NULL to return complete arrays (useful together with index_key to reindex the array).
 * @param mixed $index_key [optional] The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.
 *
 * @return array Returns an array of values representing a single column from the input array.
 */
function array_column_keys($array, $column, $index_key = null)
{
    $output = [];

    foreach ($array as $key => $item) {
        $output[@$item[$index_key] ?? $key] = @$item[$column];
    }

    return array_filter($output, function($item) {
        return null !== $item;
    });
}

The third parameter index_key is what I also needed. This will answer the question when setting third parameter to null as in following example:

$result = array_column_keys($items, 'id');

...and also let's you define the value for the key

$result = array_column_keys($items, 'id', 'any_key');

This will result in

array (size=3)
 string 'any_value1' => int 5
 string 'any_value2' => int 6
 string 'any_value3' => int 7
algorhythm
  • 8,530
  • 3
  • 35
  • 47
2

array_combine(array_keys($data), array_column($data, 'id'));

id => name of the column to display

  • While your answer may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. You can edit your answer to add explanations and give an indication of what limitations and assumptions apply. - [From Review](https://stackoverflow.com/review/late-answers/28382822) – Adam Marshall Feb 22 '21 at 18:09
0

For your example with only one column id

array_map('current', $items);
ReenExe
  • 23
  • 2
  • 1
    This is a solution for the example, but no valid solution to the problem. If you have an array with a "subarray" which does not contain a key-value pair with the key id, this pair would still be in the result, as with array_column it would not. – Flummiboy Feb 15 '17 at 09:31
  • There is nothing wrong with how this answer provides a concise solution for the sample data provided in the question. – mickmackusa Jul 30 '22 at 03:13
0

Here a more "modern-style" solution using inline arrow function (PHP7.4+):

array_map(fn($e) => $e['id'], $items);

PHP official documentation extract:

array_map() preserve the keys of the array argument if and only if exactly one array is passed

-3
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>';
}
wie5Ooma
  • 281
  • 1
  • 4
  • 15