简体   繁体   English

in_array在数组中找不到值

[英]in_array not finding value 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 当我var_dump这个数组我得到

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 . 我只得到selected once select的输出,但是我期望selected once select的输出两次

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? 我已经看到很多人在使用in_array时都遇到过类似的问题,但是我发现没有一个解决方案可以解决(大多数问题都略有不同。我尝试过翻转数组并使用array_key_exists不走运。我也尝试过preg_replace删除字符串中没有运气的空格。有人可以解释这个问题吗?

If you look the var_dump() output carefully, you can see that the string Cardiology has a space at the beginning: 如果仔细查看var_dump()输出,可以看到字符串Cardiology开头有一个空格:

string(11) " Cardiology"
            ^

This is causing in_array() to not detect it as a matching value. 这导致in_array()无法将其检测为匹配值。 To remove the space, you could apply trim on all the array elements using array_map() before doing the in_array() check: 要删除的空间,你可以申请trim使用的所有数组元素array_map()在做之前in_array()检查:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM