2

Sometimes when you are performing db queries, you might need only the first element of the arrays whereas PHP result array will give you an array of arrays containing one element each. What is the best way to extract each element into an array e.g.

Say you have array(array('silas'), array('douglas'))

but you need array('silas', 'douglas');

2
  • 3
    array_column if it's php 5.5+, foreach loop if not Commented Nov 22, 2013 at 10:22
  • 2
    There is a userland implementation of array_column() that will work with versions of PHP prior to 5.5 Commented Nov 22, 2013 at 10:23

1 Answer 1

3

You can use array_map('array_shift', $your_array);

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

4 Comments

Note that array_map is slower than foreach($your_array as $elem) { $new_array[] = array_shift($elem); }
array_column() is significantly faster than either, if it's available to use
Yeah, I've learnt that too now, but PHP 5.5+ is a bit futuristic.
Timings on an array with 256k elements: array_column time = 0.021726 s; array_map time = 0.241532 s; foreach time = 0.174203 s

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.