Online Online - 3 months ago 10
PHP Question

PHP Increment array keys +1

I'm looking for some simple solution (1 line) to increment all the keys +1 in an multi array.

Array (
0 => Array (
7 => 'foo',
13 => 'foo'
),
1 => Array (
2 => 'foo',
25 => 'foo'
),
4 => Array (
24 => 'foo'
)
)


RESULT ARRAY

Array (
1 => Array (
8 => 'foo',
14 => 'foo'
),
2 => Array (
3 => 'foo',
26 => 'foo'
),
5 => Array (
25 => 'foo'
)
)

Answer
$data = [
       0 => [7 => 'foo', 13 => 'foo'],
       1 => [2 => 'foo', 25 => 'foo'],
       4 => [24 => 'foo'],
];

// top level
$data = array_combine(
    array_map(function ($key) { return ++$key; }, array_keys($data)),
    $data
);
// then the elements (use array_walk_recursive() if you have more levels)
array_walk(
    $data,
    function(&$data) {
        $data = array_combine(
            array_map(function ($key) { return ++$key; }, array_keys($data)),
            $data
        );
    }
);
var_dump($data);

Demo