Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

arrays - php index of item

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...