0

Here’s the following array:

Array
(
    [1] => Array
        (
            [0] => 10
            [1] => 13
        )

    [2] => Array
        (
            [0] => 8
            [1] => 22
        )

    [3] => Array
        (
            [0] => 17
            [1] => 14
        )
)

Then I have

$chosenNumber = 17

What I need to know is:

First) if 17 is in the array

Second) the key it has (in this case [0])

Third) the index it belongs (in this case [3])

I was going to use the in_array function to solve first step but it seems it only works for strings ..

Thanks a ton!

1

5 Answers 5

3
function arraySearch($array, $searchFor) {
    foreach($array as $key => $value) {
        foreach($value as $key1 => $value1) {
            if($value1 == $searchFor) {
                return array("index" => $key, "key" => $key1);
            }
        }
    }

    return false;
}

print_r(arraySearch($your_array, 17));
Sign up to request clarification or add additional context in comments.

1 Comment

I forgot to return false if there is no match. I've edited the function
1

You should look using these :

in_array()
array_search()

1 Comment

I think you could improve this answer by including links to these functions in the php documentation.
0

You have used array_search function

$qkey=array_search(value,array);

1 Comment

returns false, and the element is there
0

You use array_search:

$index = array_search($chosenNumber, $myArray);
if($index){
    $element = $myArray[$index];
}else{
    // element not found
}

array_search returns false if the element was not found, the index of the element you were looking for otherwise.

If a value is in the array multiple times, it only returns the key of the first match. If you need all matches you need to use array_keys with the optional search_value parameter specified:

$indexes = array_keys($myArray, $chosenNumber);

This returns a (possibly empty) array of all indexes containing your search value.

Comments

0

array_keys()

  • Return all the keys or a subset of the keys of an array

array_values()

  • Return all the values of an array

array_key_exists()

  • Checks if the given key or index exists in the array

in_array()

  • Checks if a value exists in an array

You can find more information here http://www.php.net/manual/en/function.array-search.php

Comments

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.