PHP Changing a multidimensional array to associative array


Example

If you have a multidimensional array like this:

[
    ['foo',  'bar'],
    ['fizz', 'buzz'],
]

And you want to change it to an associative array like this:

[
    'foo'  => 'bar',
    'fizz' => 'buzz',
]

You can use this code:

$multidimensionalArray = [
    ['foo',  'bar'],
    ['fizz', 'buzz'],
];
$associativeArrayKeys   = array_column($multidimensionalArray, 0);
$associativeArrayValues = array_column($multidimensionalArray, 1);
$associativeArray       = array_combine($associativeArrayKeys, $associativeArrayValues);

Or, you can skip setting $associativeArrayKeys and $associativeArrayValues and use this simple one liner:

$associativeArray = array_combine(array_column($multidimensionalArray, 0), array_column($multidimensionalArray, 1));