Using strict on in_array in PHP

Please notice that in version 7 of PHP using of the strict parameter is important. This is the third parameter!

The following code shows you how a value of 0 validates true on an array where it is not included. Including the third (strict) parameter with a value of true will give proper result.

In PHP version 8 and higher the result is both with and without the strict value correct.

code

<?php
const VALIDATE_AS_TRUE = [1, '1', 'on', true, 'true'];
$val = 0;

echo "We test the value of 0 against an array with following values: 1, '1', 'on', true 'true' \r\n"; 

echo "\r\nWithout the strict paremeter on in_array value 0 tests true\r\n";
var_dump(in_array($val, VALIDATE_AS_TRUE));

echo "\r\nWith the strict parameter on in_array value 0 tests false\r\n";
var_dump(in_array($val, VALIDATE_AS_TRUE, true));

result (PHP version 7.x)

We test the value of 0 against an array with following values: 1, '1', 'on', true 'true' 

Without the strict paremeter on in_array value 0 tests true
bool(true)

With the strict parameter on in_array value 0 tests false
bool(false)

You can test the code with different PHP versions here.

Last update: Tue, 13 Sep 2022 14:32:15