0

I recently fixed a bug in a program where in_array was returning true for an unmatched string value. The string '$500' is not contained in the array. If you run this script the check will return true.

If you pass true for strict mode it will work. Is this a bug in PHP or is there something going on here that I don't understand?

<?php
$ZeroCheck = ["none", "zero","","0",0,"0%","$0"];

var_dump(in_array('$500', $ZeroCheck));

//returns true.. should return false.. strict works.. but why?
ladieu
  • 127
  • 5
  • 17
  • 3
    Possible duplicate of [PHP in\_array() / array\_search() odd behaviour](https://stackoverflow.com/q/2739441/1255289) – miken32 Oct 24 '18 at 02:05
  • 2
    In this case, the comparison `'$500' == 0` is true because comparing a string to an integer always converts non-numeric strings to 0. – miken32 Oct 24 '18 at 02:07
  • PHP is very loosely typed, but I recommend taking every opportunity possible to make it as strict as you can, including typecasting and strict equality checks – miken32 Oct 24 '18 at 02:08
  • 1
    @miken32 - I like it loose and fast ... – ArtisticPhoenix Oct 24 '18 at 02:11
  • *Hm...* that's odd @miken32 - Whenever a question is hammered, the comment flag as a duplicate should have disappeared; meta question worthy? – Funk Forty Niner Oct 24 '18 at 02:33
  • @JayBlanchard see my above comment ^ – Funk Forty Niner Oct 24 '18 at 02:34
  • @FunkFortyNiner LOL I was playing around with a userscript months ago that replaces question links with SO shortlinks. I'd forgotten all about it. Probably by editing the content of the comment it mucks with that process. – miken32 Oct 24 '18 at 02:36
  • @miken32 Double *"Hm"*. Yeah, well now "that" is even more bizarre and intriguing. This sounds somewhat related to [a meta question I asked this summer](https://meta.stackoverflow.com/q/371539/1415724), could be related. – Funk Forty Niner Oct 24 '18 at 03:09
  • thanks guys, I fully understand now – ladieu Oct 30 '18 at 14:41

0 Answers0