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
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With