Search code examples
phpmysqlarraysexplodeimplode

PHP explode function only allows me to detect first item of array when i search in_array. Why?


I've converted checkbox data into a string to store in my database.

However, when I try to convert the string back into an array with the explode function, I am having trouble searching in_array for anything apart from the first item. Why?

$rolepref = explode(',', $roles);
print_r($rolepref) = [0] Strategy [1] Operations
if (in_array("Strategy", $rolepref) { echo "yes" } => Will echo yes
if (in_array("Operations", $rolepref) { echo "yes" } => Does not work

What am I missing here? Thanks in advance!


Solution

  • Most probably you have white spaces after explode data. Try to explode with trim

    $roles = "Strategy, Operations";
    $rolepref = array_map('trim', explode(',', $roles)); //trim and explode data
    if (in_array("Strategy", $rolepref)) { echo "yes"; }
    if (in_array("Operations", $rolepref)) { echo "yes"; }