PHP loose type comparison: Arrays · 18 September 2009, 13:30

I was baffled by some === and == discrepancies regarding arrays, so I decided to investigate. Let me quote what I wrote on a wiki discussion page of an internal project:

Pardon me for reverting to English, but I’ll get my thoughts down faster this way.

So – I was really curious about what exactly happens when you loose-compare arrays in PHP and couldn’t let that go. Cue investigations!

…it seems like the array equality checks in PHP are quite… complex. I’ve nosed around in it and noticed that not only does it actually recurse through the array, it’s so ‘smart’ to check array keys and values. It’s actually rather hard to summarise what exactly it does, but I spent some time beating a function into shape in effort to find out what actually happens. Right now, as far as I can see, this function is unconditionally equivalent to the loose comparison of arrays that PHP does internally.

Take a look at this baffling complexity:

function looseEqualityArrayHandler($arr1,$arr2) {

// only proceed if arrays have the same amount of elements if (count($arr1)!==count($arr2)) { return false; } // iterate through elements $result = true; // assume true foreach ($arr1 as $k=>$v) { // -all- keys have to be present, by the same name (though not in the same order!) // [remember, though, that as far as array keys go ‘int’ = int, e.g. key ‘8’ is equal to key 8] if (!isset($arr2[$k])) { return false; // if both are arrays, recurse :) } else if (is_array($v) && is_array($arr2[$k])) { $result = $result && looseEqualityArrayHandler($v,$arr2[$k]); // otherwise, check values } else { // if they’re empty, we’ll consider them equal[!] $both_empty = (empty($v)) && (empty($arr2[$k])); // of course, they could be classically equal, too $result = $result && ($both_empty || ($v==$arr2[$k])); } // if false, we have our answer, break out of loop and dodge velociraptor if (!$result) { break; } } return $result;

}

Note: This is documented behaviour, you just have to know how to read the PHP example code snippet on array behaviour, where == does not appear. In fact, it’s its lack of appearance that causes ‘empty() to fire’. Take a look.

— Neike Taika-Tessaro

---

Comment

Textile Help
Categories: knowledge, php
Related:

Apache & PHP: Headache with POST / GET · 10 December 2011, 02:43

mediawiki's Special: Recent Changes bug · 30 November 2009, 15:04

Extending phpDocumentor with custom tags · 23 October 2009, 19:36

void and null function 'returns' in PHP · 22 September 2009, 16:53

Quick PHP block comment toggle · 18 September 2009, 11:58