Miguel Mas
Miguel Mas

Reputation: 545

PHP arrays: How to get the index where an element is

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!

Upvotes: 0

Views: 169

Answers (5)

Afshin
Afshin

Reputation: 4215

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

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

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));

Upvotes: 3

Olivier Kaisin
Olivier Kaisin

Reputation: 529

You should look using these :

in_array()
array_search()

Upvotes: 1

Asciiom
Asciiom

Reputation: 9975

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.

Upvotes: 0

Hkachhia
Hkachhia

Reputation: 4539

You have used array_search function

$qkey=array_search(value,array);

Upvotes: 0

Related Questions