TIL: Why PHP still sucks sometimes!

 Apr 4, 2013

While I have made my career over the last decade mostly based on PHP programming, its weird and sometimes outright insane gotcha’s still get me on a regular basis.

Today, I came right up against one with what I thought should be a relatively simple piece of coding, something I’ve done thousands of times before. Checking if a value is in an array.

// simplified version of what I was working with
$myArray = array(0, 'First String', 'Second String');

if (in_array('Third String', $myArray)) {
   $var = 'asc';
} else {
    $var = 'desc';
// code above produces:
// $var = 'asc'

Every time I ran through the above block of code, the value of $var was always asc no matter the contents of the array.

Checking the value of the in_array call always returned true

And do you know why in_array always returned true (even when it shouldn’t)…

PHP equates 0 to any string

var_dump(0 == 'any string you like'); // => true

How’s that for nice sane behaviour!


Well it appears this is actually a feature of the language.

Who am I to say what equality should be

Directly from the horses mouth on php.net

String to number conversion: If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero)

Oh, and a quick search shows up lots of bug reports about this feature so I’m not the only one, but they are all closed as “Not A Bug”

This is one of the many reasons why I get so fed up with PHP and so excited to work with other langauges. While most languages have their own quirks, none (at least so far) seem to have quite the same range and quantity as PHP.