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
See Live Demo
Quote it. 0123 without quotes is octal in PHP. It's in the docs
This has been answered in stackoverflow before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With