0

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

1 Answer 1

4

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.

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

5 Comments

This comment is not for @Nick as your answer is great and no matter what we say you just answered the OP question.This comment is for the OP himself :Hi.I understand your question.However do you know that if the key your are searching is in the first case and the length of your array is for example 1000000 or more you will make your server work for absolutely nothing. It will execute array_column first and then array_search
for the OP:I think that in some cases foreach is the better solution.Think about it....
@Elementary I updated my answer with some benchmarking data fyi
Great answer, I toyed around for a while to see if I could come up with something faster/different. This is the clear winner.
Good job... Your answer was/is great no matter what we say. I hope the OP will do an optimal choice according to the length of his array because this is not necessarly the solution for every search...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.