Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's variable type leniency

Tags:

php

The most recent comment on PHP's in_array() help page (http://uk.php.net/manual/en/function.in-array.php#106319) states that some unusual results occur as a result of PHP's 'leniency on variable types', but gives no explanation as to why these results occur. In particular, I don't follow why these happen:

// Example array

$array = array(
    'egg' => true,
    'cheese' => false,
    'hair' => 765,
    'goblins' => null,
    'ogres' => 'no ogres allowed in this array'
);

// Loose checking (this is the default, i.e. 3rd argument is false), return values are in comments
in_array(763, $array); // true
in_array('hhh', $array); // true

Or why the poster thought the following was strange behaviour

in_array('egg', $array); // true
in_array(array(), $array); // true

(surely 'egg' does occur in the array, and PHP doesn't care whether it's a key or value, and there is an array, and PHP doesn't care if it's empty or not?)

Can anyone give any pointers?

like image 771
ChrisW Avatar asked Nov 24 '11 14:11

ChrisW


1 Answers

763 == true because true equals anything not 0, NULL or '', same thing for array because it is a value (not an object).

To circumvent this problem you should pass the third argument as TRUE to be STRICT and thus, is_rray will do a === which is a type equality so then

763 !== true

and neither will array() !== true

like image 74
Mathieu Dumoulin Avatar answered Oct 03 '22 08:10

Mathieu Dumoulin