I have a large array of arrays and each of these sub-arrays has an ID and some other info. Is there a way to access an array of just the ID's without using a loop?

Sort of like

$array[ALLOFTHEITEMS][Id]; 

I want to eventually compare these ID's to another flat array of ID's. I would usually do a for loop and then just add the id of each item to a new array and then compare them. But is there a faster way?

share|improve this question

feedback

1 Answer

up vote 2 down vote accepted

Not sure if its faster then foreach as I've never benchmarked it but an alternative to foreach would be:

php 5.3

$ids = array_map(function($data) { return $data['id']; }, $array);

php < 5.3

function reduceToIds($data) {
    return $data['id'];
}

$ids = array_map('reduceToIds', $array);

I normally use the foreach approach myself though.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
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.