In_array () no longer works as expected if the array is created using explode ()

First, I am changing the string to an array. And when I try to search within that array, the search for the value of the second array fails. Below is my code.

//my string
$a = 'normal, admin';
//Change string to array
$arr = explode(",",$a);
// Search by array value
dd(in_array("admin", $arr)); //got false

      

But when I try to find something like the following it works.

//my string
$a = 'normal, admin';
//Change string to array
$arr = explode(",",$a);
// Search by array value
dd(in_array("normal", $arr)); //got true

      

+3


source to share


3 answers


This is because the admin

leading space matters from explode()

! You can see this if:

var_dump($arr);

      

Output:



array(2) {
  [0]=>
  string(6) "normal"
  [1]=>
  string(6) " admin"
       //^   ^ See here
}

      

To solve this problem, simply apply trim()

in conjunction with array_map()

for each array value, for example:

$arr = array_map("trim", $arr);

      

+4


source


Yes, the first one won't work as you might see extra space there before yours admin

, which won't work, need to use functions trim

and array_map

check the result before

$a = 'normal, admin';
//Change string to array

$arr = array_map('trim',explode(",",$a));
// Search by array value
var_dump($arr);
var_dump(in_array("admin", $arr));

      



output:

array(2) { [0]=> string(6) "normal" [1]=> string(5) "admin" } bool(true)

      

+2


source


You have an array from a string like this: String:

$a = 'normal, admin';

      

After using the explosion, an array like this will appear:

$arr = array('normal',' admin');

      

I mean, you have a place in admins, why not looking for an admin in a function in_array

.

Solution: Before using blast, use this function:

$newstr = str_replace(" ", "", $a);
$arr = explode(',',$newstr);

      

+1


source







All Articles