项目的php索引 [英] php index of item
问题描述
我有一个看起来像这样的数组:
$fruit = array('apple','orange','grape');
如何在上述数组中找到特定项目的索引?(例如,值 'orange')
试试 array_search 功能.
来自手册中的第一个示例:
<块引用> '蓝色', 1 => '红色', 2 => '绿色', 3 => '红色');$key = array_search('green', $array);//$key = 2;$key = array_search('red', $array);//$key = 1;?>
注意事项
比较结果时,请确保使用 ===
运算符显式测试值 false
.
由于 PHP 中的数组是从 0 开始的,如果您要搜索的元素是数组中的第一个元素,则将返回值 0.
虽然 0 是一个有效的结果,但它也是一个假值,意味着以下将失败:
'蓝色', 1 => '红色', 2 => '绿色', 3 => '红色');$key = array_search('blue',$array);if($key == false) {throw new Exception('找不到元素');}?>
这是因为 ==
运算符检查 相等(通过类型杂耍),而 ===
运算符检查 身份.
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')
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.
这篇关于项目的php索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!