I’ve struggled with the php in_array() function all morning. Eventually I was able to fix it but I’m a bit confused about why the setting fixed the problem.
I set the variable $type to a string value(‘forum’ to be exact), and the $all_types to an array looking like this:
$all_types:
[protocol2] => protocol2
[group] => 0
[post] => 0
[forum] => 0
[article] => 0
[page] => 0
[protocol1] => 0
And then I had:
if (in_array($type,$all_types) !== FALSE) {
"Do stuff..."
}
And “Do stuff…” kept happening. First I thought it was because it hit on the ‘forum’ key in the array so I tried changing the array to:
[0] => protocol2
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 0
But it still didn’t work. Finally I set the STRICT variable to TRUE and it seems to work fine, even with the original array.
So why is this? STRICT = TRUE meant the needle and the value in the haystack had to be of the same type, but aren’t they both strings when they do match? And when they don’t you compare ‘forum’ to 0, and does that for some reason match?
It is for Type Juggling. When you using ‘STRICT’ as FALSE, in_array compares values using ‘==’ operator.
And you know,
var_dump('string' == 0);is true.So, when you have different types of values in an array, it’s always good to compare it with strict comparison.
http://www.php.net/manual/en/language.operators.comparison.php