3

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

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

$arr = array_amp("trim", $arr); is$arr = array_map("trim", $arr); ? It's work. Thanks
2

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)

1 Comment

@SetKyarWaLar you can accept one of these answers that'll make this answer to be considered as solved.Thank You.
1

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

$a = 'normal, admin';

After use of explode there will come any array like this:

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

I mean to say you have a space in admin that's why is not searching the admin in in_array function.

Solution: Before using the explode use this function:

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

Comments

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.