Chrisstar Chrisstar - 1 year ago 118
PHP Question

Add Dimension in PHP array

I'm looking for a solution to add an dimension to a php array. As this title is confusing Ill give you an example.
If I have the array:

[0] => 'xx1',
[1] => 'xx2',
[2] => 'xx3',

I want to convert it to

[0] => 'y' => 'xx1',
[1] => 'y' => 'xx2',
[2] => 'y' => 'xx3',

Is there a way to do this without using a loop?

Answer Source

There's not a way to do it without touching each element, but with array_map you can do it without explicitly using a loop.

$new_array = array_map(function($x) {
    return ['y' => $x];
}, $your_array);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download