-2

While developing a PHP application, I ran into this strange quirk.

Apparently, the string '01' == '1', '05' == '5', '03111' == '3111'. I tried this -

php > $numbers = ["1", "2", "3", "4", "5"];
php > in_array("01", $numbers);
true
php > var_dump("01" == "1");
true
php > var_dump("00003333" == "3333")
true

How do I prevent this (i.e return false for the in_array call) , and why is it happening in the first place?

Joseph
  • 1,003
  • 3
  • 11
  • 25
  • use 3 equals signs `===` – 123 Aug 03 '16 at 13:27
  • PHP's manual has some guidelines on variable types and their effect in comparisons. http://php.net/manual/en/language.operators.comparison.php – Geoff Atkins Aug 03 '16 at 13:31
  • FYI: `in_array()` does a loosely comparison by default, so it is basically the same as `==` and for that also the same reason why it works the same way. It also is the same solution for solving it with `==` and `in_array()` to just use identical comparison. – Rizier123 Aug 03 '16 at 13:34

1 Answers1

0

You should use strict comparison in in_array

in_array("01", $numbers, true);

and === instead of == then php compare also types

quentino
  • 1,101
  • 1
  • 10
  • 25