4

Let's assume I have an array of elements, which are arrays themselves, like so:

$array = [
    ['foo' => 'ABC', 'bar' => 'DEF'],
    ['foo' => 'ABB', 'bar' => 'DDD'],
    ['foo' => 'BAC', 'bar' => 'EFF'],
];

To set the values of the foo field as the key of the array I could do this:

foreach ($array as $element) {
    $new_array[$element['foo']] = $element;
}
$array = $new_array;

The code is naturally trivial, but I've been wondering whether there's an in-built that can do the same for me.

Rahul
  • 18,271
  • 7
  • 41
  • 60
Ivan T.
  • 525
  • 5
  • 19

3 Answers3

8

Notice array_column can get index as well (third argument):

mixed $index_key = NULL

So just use as:

array_column($array, null, 'foo');
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
dWinder
  • 11,597
  • 3
  • 24
  • 39
3

Here is one liner for your case,

$temp = array_combine(array_column($array, 'foo'), $array);

Working demo.

array_combine — Creates an array by using one array for keys and another for its values
array_column — Return the values from a single column in the input array

Rahul
  • 18,271
  • 7
  • 41
  • 60
0

You can also do it with array_reduce

$new_array = array_reduce($array, function($carry, $item) {
    $carry[$item['foo']] = $item;
    return $carry;
}, []);
jakub wrona
  • 2,212
  • 17
  • 17