myol myol - 6 months ago 10
PHP Question

Pushing multidimensional arrays as keys on another array

I have an empty array (as an example) and a number of multidimensional arrays I would like to push onto this array. However I would like the keys of each multidimensional array to become a key of the empty array

Using

$myEmptyArray[] = $arrayOne;
$myEmptyArray[] = $arrayTwo;
$myEmptyArray[] = $arrayThree;


I get

[
0 => ['one' => ['a' => 'stuff']],
1 => ['two' => ['b' => 'stuff']],
2 => ['three' => ['c' => 'stuff']]
]


I would prefer to have

[
'one' => ['a' => 'stuff'],
'two' => ['b' => 'stuff'],
'three' => ['c' => 'stuff']
]


What is a neat and compact way (one liner or native php function) to do this without having to read the array key with a foreach and then assign this key explicitly to the empty array with the value like

foreach ($arrayOne as $key => $value) {
$myEmptyArray[$key] = $value
}


As I will want to use this in many places in my code

Answer

You can use the + (union) operator which "returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored".

$array = [];
$array += ['one' => ['a' => 'stuff']];
$array += ['two' => ['b' => 'stuff']];
$array += ['three' => ['b' => 'stuff']];
var_dump($array);
/*
array(3) {
  'one' =>
  array(1) {
    'a' =>
    string(5) "stuff"
  }
  'two' =>
  array(1) {
    'b' =>
    string(5) "stuff"
  }
  'three' =>
  array(1) {
    'b' =>
    string(5) "stuff"
  }
}
*/
Comments