php index of item

90,585

Solution 1

Try the array_search function.

From the first example in the manual:

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

A word of caution

When comparing the result, make sure to test explicitly for the value false using the === operator.

Because arrays in PHP are 0-based, if the element you're searching for is the first element in the array, a value of 0 will be returned.

While 0 is a valid result, it's also a falsy value, meaning the following will fail:

<?php
    $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');   

    $key = array_search('blue',$array);

    if($key == false) {
        throw new Exception('Element not found');
    }
?>

This is because the == operator checks for equality (by type-juggling), while the === operator checks for identity.

Solution 2

have in mind that, if you think that your search item can be found more than once, you should use array_keys() because it will return keys for all matching values, not only the first matching key as array_search().

Regards.

Share:
90,585
mcgrailm
Author by

mcgrailm

Hello, thanks for visiting my profile. I am a web developer at PSU. I started my carrier by learning applescript. Since then I've become familiar with PHP MySQL, javascript, jQuery as well. I have made use of other services that go hand and hand with those languages such as json,jsonp,ajax. I have some shell scripting experience and have dabbled in perl. Hopefully I have helped you with a question you or maybe you have help me with a question, thanks for stopping by.

Updated on July 30, 2020

Comments

  • mcgrailm
    mcgrailm almost 4 years

    I have an array that looks like this:

    $fruit = array('apple','orange','grape');
    

    How can I find the index of a specific item, in the above array? (For example, the value 'orange')

  • mcgrailm
    mcgrailm about 13 years
    Return Values Returns TRUE if needle is found in the array, FALSE otherwise.
  • mcgrailm
    mcgrailm about 13 years
    I think doing the if(in_array(. bit should protect me from the problme you noted after "be careful"
  • Dmitry Gamolin
    Dmitry Gamolin almost 7 years
    There's a small error in the code, the array is not specified. It should be array_search('blue', $array).