Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
Do you wish to extract all data? or specifics. –  Daryl Gill Apr 5 '13 at 22:59
    
I need an array with just the numbers in, so array(76, 65, 59) –  Dan Apr 5 '13 at 23:01

4 Answers 4

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

share|improve this answer
    
I just tested this and it worked perfectly setting $newArray with the values you require. –  Peter Featherstone Apr 5 '13 at 23:36

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)

share|improve this answer
    
I'm just looking at array_walk now. My desired output is array(76, 65, 59) - will array_walk do this? –  Dan Apr 5 '13 at 23:05
    
see this answer: stackoverflow.com/questions/15844965/… ;) –  bwoebi Apr 5 '13 at 23:07

Try:

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

That should convert the array into the format you want.

share|improve this answer
    
What is finally the same as: foreach ($array as &$v) $v = $v[0]; –  bwoebi Apr 5 '13 at 23:09
    
Sure, he asked for a way to do it without foreach though. array_walk has the advantage that $v doesn't pollute the name space. –  Michael Thessel Apr 5 '13 at 23:14

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.