php index of item

前端 未结 3 1986
闹比i
闹比i 2020-12-15 15:02

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 a

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 15:45

    Try the array_search function.

    From the first example in the manual:

     '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:

     '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.

提交回复
热议问题