Reputation: 827
I want to get the index of an array without foreach. this is sample array
Array
(
[0] => Array
(
[gcr_distance] => 31.0
[gcr_id] => 23
)
[1] => Array
(
[gcr_distance] => 28.0
[gcr_id] => 22
)
[2] => Array
(
[gcr_distance] => 26.0
[gcr_id] => 20
)
[3] => Array
(
[gcr_distance] => 110.0
[gcr_id] => 21
)
)
suppose if my data is gcr_id=21, by comparing with the above array it should give me an index of array 3
Upvotes: 0
Views: 43
Reputation: 147146
You can use a combination of array_search
and array_column
. array_column
returns all the values which have a key of 'gcr_id'
and then array_search
returns the key which corresponds to a value of 21
.
$array = array(
array('gcr_distance' => 31.0, 'gcr_id' => 23),
array('gcr_distance' => 28.0, 'gcr_id' => 22),
array('gcr_distance' => 26.0, 'gcr_id' => 20),
array('gcr_distance' => 110.0, 'gcr_id' => 21)
);
$key = array_search(21, array_column($array, 'gcr_id'));
echo $key;
Output:
3
Inspired by @Elementary's comment, I did some bench testing on this. What I found was that on a 100k entry array, array_search
and array_column
took around 80% of the time that a foreach
based search took when the entry was not in the array, 95% of which was in the call to array_column
. So it would seem that on average, a foreach
based search would be faster.
Upvotes: 4