I have an array of 0845 numbers that is being searched via in_array for a specific numbers. For some reason, omitting the leading zero from the needle returns a false positive:
$numbers = array(
'08451234567',
'08452345678',
'08453456789',
'08454567890',
...
);
var_dump(in_array('08451234567', $numbers)); //(Boolean) TRUE - Right
var_dump(in_array('8451234567', $numbers)); //(Boolean) TRUE - Wrong
I have tried casting the values in the array as strings, but that did not work.
What is going on, and how do I fix it?
[edit]
Added quote around my needles
Use strict comparision
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
Use
var_dump(in_array("08451234567", $numbers,true)); //(Boolean) true - OK
var_dump(in_array("8451234567", $numbers,true)); //(Boolean) false - OK
Why
var_dump(08451234567); // returns 0 because its octal
var_dump((int) "08451234567"); // returns 8451234567
var_dump((float) "08451234567"); // returns 8451234567
Only
var_dump("08451234567" === "08451234567"); // returns true
Wrap the number with '
else the leading 0
will be ignored and the value will be converted to an integer.
var_dump(in_array('08451234567', $numbers));
var_dump(in_array('8451234567', $numbers));
Quote it. 0123 without quotes is octal in PHP. It's in the docs
This has been answered in stackoverflow before.