1

Suppose I have the following array:

$enabled = array(
  'page' => 'page',
  'article' => 0,
);

Note "article" is a key, but not a value. Since in_array() searches for matching values, I would expect the following line to return FALSE:

in_array('article', $enabled)

Yet, it returns TRUE. Why? What am I missing?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Joel Stein
  • 13
  • 2

2 Answers2

7

The function in_array() by default performs a loose comparison and this causes PHP to evaluate the expression (0 == "article") as TRUE.

You need to use the strict parameter for in_array() to also check the types of the needle in the haystack:

var_dump( in_array('article', $enabled, true) );

Demo!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • Thanks! I'm still confused why "article" would == 0, since I would assume it would == "1" if anything. Can you point to documentation which explains this? I appreciate the answer. – Joel Stein Oct 09 '13 at 16:06
  • @JoelStein: Here you go: [php.net/manual/en/language.types.string.php](http://php.net/manual/en/language.types.string.php#language.types.string.conversion) – Amal Murali Oct 09 '13 at 16:13
0

Pass the third parameter for strict type checking:

in_array('article', $enabled, true);

Otherwise, PHP will try to compare 0 (integer) and 'article' (string).
'article' evalutes to 0!
→They're equal!

Example @ codepad.org

ComFreek
  • 29,044
  • 18
  • 104
  • 156