Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to assign keys to array elements in PHP from a value column with less code?

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.

like image 641
Ivan T. Avatar asked Dec 17 '22 17:12

Ivan T.


1 Answers

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

mixed $index_key = NULL

So just use as:

array_column($array, null, 'foo');
like image 73
dWinder Avatar answered May 02 '23 18:05

dWinder