php索引项 [英] php index of item

查看:117
本文介绍了php索引项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数组:

I have an array that looks like this:

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

如何在上面的数组中找到特定项目的索引? (例如,值'orange')

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

推荐答案

尝试 array_search 函数。

从手册中的第一个示例:

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


提醒

比较结果时,请务必使用 ==显式测试值 false = 运算符。

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

因为PHP中的数组是基于0的,如果您要搜索的元素是数组中的第一个元素,则返回值0。

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.

虽然0是有效结果,但它也是一个假值,意味着以下将失败:

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');
    }
?>

这是因为 == 运算符检查for equality (通过type-juggling),而 === 运算符检查 identity

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

这篇关于php索引项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆