美文网首页
php array_search

php array_search

作者: 小易哥学呀学 | 来源:发表于2021-11-06 11:45 被阅读0次

用法

搜索值,返回键名

<?php

$res = array_search("red", ["red", "blue"]);

echo $res;

输出

0

 

返回结果

如果在数组中,找到该值,返回该值键名。
如果在数组中,没找到该值,返回false。
如果第二个参数不是数组,返回NULL。
 

函数原型

needle:要在数组中搜索的值
haystack:数组
strict:类型与值均匹配

array_search(mixed $needle, array $haystack, bool $strict = false): mixed

 

注意事项(1)

第二个参数如果不是数组:

返回结果为NULL,并Warning。

<?php

$needle = "red";
$haystack = "一个字符串,而非数组";

$res = array_search($needle, $haystack);

var_dump($res);

输出

Warning: array_search() expects parameter 2 to be array, string given in test.php on line 7
NULL

 

注意事项(2)

注意大小写:
<?php

$needle = "red";
$haystack = ["Red", "blue"];

$res = array_search($needle, $haystack);

var_dump($res);

输出

bool(false)

 

注意事项(3)

needle 在 haystack 中出现不止一次:

返回第一个匹配的键。

<?php

$needle = "red";
$haystack = ["red", "red"];

$res = array_search($needle, $haystack);

var_dump($res);

输出

int(0)

 

注意事项(4)

第三个参数的使用:

返回第一个匹配的键。

<?php
$needle = 1;
$haystack = ["red", true];

$res1 = array_search($needle, $haystack);
$res2 = array_search($needle, $haystack, true);

var_dump($res1);
var_dump($res2);

输出

int(1)
bool(false)

相关文章

网友评论

      本文标题:php array_search

      本文链接:https://www.haomeiwen.com/subject/eecezltx.html