下面是我从css文件中获取的类名称数组
test array after printing values:
Array
(
[0] => #sa_nav
[1] => #sa_nav ul li.account
[2] => .loyaltyBox
)
if(array_search("#sa_nav",$test))
{
echo 'Element is exist';
}
else
{
echo 'Element is not exist';
}
尽管元素存在于数组中,但它会打印“元素不存在”。请帮助
发布于 2013-03-11 06:53:30
使用in_array
函数
$test = array("#sa_nav", "#sa_nav ul li.account", ".loyaltyBox");
if (in_array("#sa_nav", $test)) {
echo 'Element is exist';
} else {
echo 'Element is not exist';
}
//输出
Element is exist
发布于 2013-03-11 06:54:22
array_search的作用是在数组中搜索给定值,如果成功,则返回相应的键
所以这意味着它不会返回true或false,所以使用in_array()
函数。
in_array
-检查值是否存在于数组中
$test = array("#sa_nav","#sa_nav ul li.account",".loyaltyBox");
if(in_array("#sa_nav",$test))
{
echo 'Element is exist';
}
else
{
echo 'Element is not exist';
}
用于搜索和返回真实FASLE的
function search_array($arrays, $cssSelector)
{
foreach($arrays as $key => $array)
{
if ( $array === $cssSelector )
return true;
}
return false;
}
并将其称为search_array($array,'#sa_nav');
发布于 2013-03-11 07:01:08
array_search()搜索值,如果匹配,则返回相应的键。
现在在你的情况下-
#sa_nav密钥值为0
所以在IF
循环中,它的计算结果是这样的-
array_search("#sa_nav",$test) return value is `0` [Zero].
因此,该表达式的计算结果为-
if(0)
所以它输出-
Element is not exist
否,如果您尝试使用此代码块,它的计算结果将为true
$test = array("#sa_nav","#sa_nav ul li.account",".loyaltyBox");
if(array_search(".loyaltyBox",$test))
{
echo 'Element is exist';
}
else
{
echo 'Element is not exist';
}
要使您的代码片段工作,您可以尝试使用in_array()
方法,正如大多数其他答案中所建议的那样。
https://stackoverflow.com/questions/15332775
复制相似问题