donglangtun1850
2014-04-13 09:34
浏览 58
已采纳

in_array在数组中找不到值

I have an array formed by exploding a string as follows.

$interest_array = explode(',', $user->interests);

When I var_dump this array I get

array(3) { 
    [0]=> string(19) "Acute critical care" 
    [1]=> string(11) " Cardiology" 
    [2]=> string(20) " Computed Tomography"
}

With the following code

if (in_array('Acute critical care', $interest_array)) {
        echo "selected";}

I output....selected. Now thats fine, but I need this to work for several of the array values. With the following code for example,

if (in_array('Acute critical care', $interest_array)) {
    echo "selected_once";
}

if (in_array('Cardiology', $interest_array)) {
    echo "selected_twice";
}

I only get one output of selected once, but I am expecting an output of selected once twice.

Why is this. I have seen that many people have had similar issues with in_array but none of the solutions I have found work (and most of the questions are slightly different. I have tried flipping the array and using array_key_exists without luck. I have also tried preg_replace to remove the white space within the string without luck. Can someone explain what the issue is?

图片转代码服务由CSDN问答提供 功能建议

我有一个通过爆炸字符串形成的数组,如下所示。

  $ interest_array = explode(',',$ user-> interest); 
   
 
 

当我 var_dump我得到这个数组

  array(3){
 [0] =>  string(19)“急性重症监护”
 [1] =>  string(11)“Cardiology”
 [2] =>  string(20)“Computed tomography”
} 
   
 
 

使用以下代码

  if(in_array(  '急性重症监护',$ interest_array)){
 echo“selected”;} 
   
 
 

我输出....已选中。 现在没关系,但我需要这个才能适用于几个数组值。 例如,使用以下代码,

  if(in_array('Acute critical care',$ interest_array)){
 echo“selected_once”; 
} 
 
if  (in_array('Cardiology',$ interest_array)){
 echo“selected_twice”; 
} 
   
 
 

我只获得一次选择的输出 ,但我希望输出一次 两次

为什么会这样。 我已经看到很多人在使用in_array时遇到了类似的问题,但是我找不到任何解决方案(大多数问题都略有不同。我试过翻转数组并使用 array_key_exists 没有运气。 我也尝试过 preg_replace 来删除字符串中的空格而没有运气。有人能解释一下这是什么问题吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题