5

I'm just wondering if it's possible to extract values from an array, in PHP, without having to loop through. Here's part of my array so you know what I mean;

Array
(
[0] => Array
    (
        [0] => 76
        [1] => Adventures of Huckleberry Finn
    )

[1] => Array
    (
        [0] => 65
        [1] => Adventures of Huckleberry Finn
    )

[2] => Array
    (
        [0] => 59
        [1] => Bookcases
    )
)

I'm after the integer [0] from each array - is there a function that can do this quicker than a foreach loop (the way I normally do this) ?

Thanks.

Dan
  • 550
  • 4
  • 10
  • 21

5 Answers5

10

Sure you are looking for the array_column function.

$newArray = array_column($originalArray,'0');

As said in PHP Manual, with this function you can extract, from an array of arrays, the only information you need. It is normally used with Associative arrays, but you can use a number as parameter and it will work as well.

ericek111
  • 575
  • 7
  • 15
Liz
  • 123
  • 1
  • 6
1

Go for a clear loop, your fellow coders will thank you. It's probably about as fast of faster then any other solution, and clear cut code is preferable over obscure loop-dodging.

Just as an illustration: how many seconds would it take you to see what:

list($b) = call_user_func_array('array_map',array_merge(array(null),$a));

...does?

Does the trick. Don't use it.

Wrikken
  • 69,272
  • 8
  • 97
  • 136
0

You eventually mean array_walk ... but this also some sort of loop? Then: the answer is no.

And I don't think that there is any quicker method (except from writing your own extension in C :-P)

bwoebi
  • 23,637
  • 5
  • 58
  • 79
  • I'm just looking at array_walk now. My desired output is array(76, 65, 59) - will array_walk do this? – Dan Apr 05 '13 at 23:05
  • see this answer: http://stackoverflow.com/questions/15844965/php-extract-values-from-multidimensional-array-without-a-loop/#answer-15845034 ;) – bwoebi Apr 05 '13 at 23:07
0

Try:

array_walk($array, function(&$v) { $v = $v[0]; });

That should convert the array into the format you want.

Michael Thessel
  • 706
  • 5
  • 20
0

You would probably be looking for array_walk()

$newArray = array();
$myCallback = function($key) use(&$newArray){
  $newArray[] = $key[0];
};

array_walk($myArray, $myCallback);

This would be of course if you had your array above in variable $myArray

Zeffr
  • 9
  • 1