Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array() doesn't work anymore as expected if the array is created with explode()

Firstly, I change my string to array. And when I try to search within that array can't search second array value. The 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 search something like the following, it's work.

//my string
$a = 'normal, admin';
//Change string to array
$arr = explode(",",$a);
// Search by array value
dd(in_array("normal", $arr)); //got true
like image 463
Set Kyar Wa Lar Avatar asked Jun 22 '26 18:06

Set Kyar Wa Lar


2 Answers

This is because value admin has a leading space from the explode()! You can see this if you do:

var_dump($arr);

Output:

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

To now solve this problem, simply apply trim() combined with array_map() to every array value like this:

$arr = array_map("trim", $arr);
like image 154
Rizier123 Avatar answered Jun 25 '26 07:06

Rizier123


Yes the first one will not work as you can see there's an extra space before your admin that'll won't work need to use trim and array_map function before checking the result

$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)
like image 40
Narendrasingh Sisodia Avatar answered Jun 25 '26 08:06

Narendrasingh Sisodia