php 项目的php索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6046908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php index of item
提问by mcgrailm
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')
如何在上述数组中找到特定项目的索引?(例如,值 'orange')
回答by Tufan Bar?? Y?ld?r?m
Try the array_searchfunction.
试试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; ?>
<?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.
比较结果时,请确保false
使用===
运算符显式测试值。
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.
因为 PHP 中的数组是基于 0 的,如果您要搜索的元素是数组中的第一个元素,则将返回值 0。
While 0 is a valid result, it's also a falsy value, meaning the following will fail:
虽然 0 是一个有效的结果,但它也是一个假值,这意味着以下将失败:
<?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.
这是因为==
运算符检查相等性(通过类型杂耍),而===
运算符检查identity。
回答by Mihail Dimitrov
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().
请记住,如果您认为您的搜索项可以被多次找到,您应该使用array_keys()因为它将返回所有匹配值的键,而不仅仅是第一个匹配键作为array_search()。
Regards.
问候。
回答by Nicola Peluchetti
You have to use array_search.
你必须使用array_search。
Look here http://www.php.net/manual/en/function.array-search.php