4

Is there an idiomatic way (some existing function) to reduce

[[0 => 'zero'], [1 => 'one']]

to

[0 => 'zero', 1 => 'one']

?

It is easy to just create a loop that does the job, but it seems inefficient, and I would clearly prefer a one-liner here.

Edit: Oh, and it is just random here that 0 and 1 follow each other. The array could also be [[2 => 'two'], [3 => 'three']]

2
  • 1
    when downvote, please state in a comment why. I find my question totally valid Commented Sep 12, 2019 at 13:56
  • 1
    @FedericoklezCulloca right, I don't. I just heart about the tendency on SO to just distribute downvotes here and there migh drives the entire network less usable. This is a bad tendency and I try to counteract it, when possible. But for me personally, yeah, whatever Commented Sep 12, 2019 at 14:02

2 Answers 2

6

You can use array_merge with ... splat operator

$a = [[0 => 'zero'], [1 => 'one']];
print_r(array_merge(...$a));

Solution II: Preserve keys

$a = [[1 => 'one'], [0 => 'zero']];
$r = [];
array_walk($a, function($v, $k) use (&$r){ $r += $v;});
print_r($r);

Working demo : https://3v4l.org/9sRaE

Sign up to request clarification or add additional context in comments.

6 Comments

Or call_user_func_array when ... is not supported.
Wow, that's what I call a one-liner!
Note that this ignores the keys in the original array, so if [1 => 'one'] is the first item in the array it becomes 0 => 'one' in the output: 3v4l.org/6UopE
@naththedeveloper oh, but this is actually important here
@IceFire solution II has the preserve keys
|
0

Assuming that you want keys preserved, and assuming that in the case of conflicting keys, you want the first value, array_reduce is well-suited to the task.

$r = array_reduce($a, function ($acc, $v) { return $acc + $v; }, []);

This is functionally identical to @Rakesh Jakhar's solution. I think it's semantically more faithful to the problem and avoids having the initialize $r and the use clause.

In php 7.4, this could be written a bit nicer with an arrow function:

$r = array_reduce($a, fn($acc, $v) => $acc + $v, []);

https://www.php.net/manual/en/function.array-reduce.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.