strpos()返回错误的结果

时间:2012-12-05 17:34:28

标签: php strpos

我的问题是我在阵列5,12中有两个数字我的问题是下面的代码返回“1”为真,因为数字12中的“1” - 它看到12中的数字1。我怎么办?告诉它阅读整个号码。

<?php 
$pos = strpos($foo,"1");

if($pos === false) {
    // do this if its false
    echo "<img src='../PICS/no.png' width='20' height='20' />"; 
}
else {
    echo "<img src='../PICS/yes.png' width='20' height='20' />"; 
} 
?>

2 个答案:

答案 0 :(得分:4)

这是您正在使用的功能的签名:

  

int strpos( string $ haystack,mixed $ needle [,int $ offset = 0])

如果你用数组作为第一个参数喂它......

<?php
$foo = array(5,12);
$pos = strpos($foo,"1");

...数组将被转换为字符串,你会收到通知......

  

警告:strpos()要求参数1为字符串,给定数组为

结果字符串将包含“Array”,字面意思是:

var_dump( @(string)array(5,12) ); // string(5) "Array"

您对1的搜索将始终失败,因为Array不包含它。

答案 1 :(得分:3)

使用 in_array()

if (in_array(1,$myarray)){
    // found in the array
}
相关问题