in_array not finding value in array
Question
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?
Solution
If you look the var_dump()
output carefully, you can see that the string Cardiology
has a space at the beginning:
string(11) " Cardiology"
^
This is causing in_array()
to not detect it as a matching value. To remove the space, you could apply trim
on all the array elements using array_map()
before doing the in_array()
check:
$interest_array = explode(',', $user->interests);
$interest_array = array_map('trim', $interest_array);