我应该如何更改代码以查找类似22的数字,并且元素是不应该找到20和12的字符串?
我想要这样的输出:
未找到12 - 12在字符串中找到, 发现22 未找到20 - 20在字符串中找到
这是我的代码
$list = array("c12", 33, 6, "020b", 22, 31);
function search($in, $what)
{
foreach($in as $item)
{
if ($item === $what)
{ return "found $what"; }
}
return "not found $what";
}
echo search($list, 12);
echo "\n";
echo search($list, 22);
echo "\n";
echo search($list, 20);
答案 0 :(得分:0)
使用
is_numeric ( $what )
如果是数字则返回true,如果是字符串
则返回false foreach($in as $item)
{
//check if numeric
if(is_numeric ( $what )){
if ($item === $what){
return "found $what";
}
}
}
答案 1 :(得分:0)
所以你需要匹配确切的值和数据类型?您最好的选择是使用in_array()功能:
<?php
$list = array("c12", 33, 6, "020b", 22, 31);
function search($in, $what)
{
if(in_array($what, $in, true))
return "found $what";
return "not found $what";
}
echo search($list, 12);
echo "\n";
echo search($list, 22);
echo "\n";
echo search($list, 20);
echo "\n";
?>
答案 2 :(得分:0)
PHP in_array
函数可以帮助您。
$list = array("c12", 33, 6, "020b", 22, 31);
if(in_array('22', $list)
{ echo search($list, 12);}