2

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?

1 Answer 1

5

If you look the var_dump() output carefully, you can see that the string Cardiologyhas 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);
Sign up to request clarification or add additional context in comments.

1 Comment

@GhostRider: Glad I could be of help. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.