Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP in_array ignoring leading zeros

Tags:

php

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

like image 437
Richard Parnaby-King Avatar asked May 07 '13 10:05

Richard Parnaby-King


2 Answers

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

like image 129
Baba Avatar answered Oct 29 '22 09:10

Baba


Quote it. 0123 without quotes is octal in PHP. It's in the docs

This has been answered in stackoverflow before.

like image 34
PHP Rocks Avatar answered Oct 29 '22 09:10

PHP Rocks