在PHP中比较字符串值和数组中的字符串值时出错

时间:2015-09-15 06:33:23

标签: php arrays string compare

我试图比较2个值,一个来自后期数据而另一个来自一个数组,奇怪的是,当我比较它们时,所有记录显示它们不相等但有些值的值相等:

我实际需要做的是取消设置发送的后期数据中不相等的值。

$a = $_POST['time']; (Value is 01:03)

$testarray = array("12:30","01:03","03:30");

for($x = 0; $x < count($testarray);$x++){
  if($a === $testarray[$x]){
    echo "ok";
  }
  else
  {
    echo "not";
  }
}

我的所有结果都没有显示,即使数组中的某个内容有类似的值。

这里似乎有什么问题?我检查了值,数据类型都是字符串。

2 个答案:

答案 0 :(得分:1)

简单使用 in_array 来检查数组中是否存在值

 $a = $_POST['time'];
 $testarray = array("12:30","01:03","03:30");

if (in_array($a, $testarray))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }

答案 1 :(得分:1)

使用in_array

$a = $_POST['time']; //(Value is 01:03)

$testarray = array("12:30","01:03","03:30");


if( in_array($a, $testarray))
{
    echo "ok";
}
else
{
    echo "not";
}