PHP array “functions”: a nightmare for functional programmers

Well, I used to think PHP itself was. But the language as a whole (no closures, no packages or namespaces, poor man’s single dispatch OO, could come up with a bunch of more things) is nothing compared to its low-level array API.

Walking an array on a low level, i.e. getting at the previous and next elements in natural array order, is done with the prev() and next() functions. The problem is that those only work as a function in that they return the corresponding array value ($val = next($array)). Besides that they act as procedures modifying internal array state. Read that again: those things have more side-effects than you can twist around in your brain, and their very core functionality relies on them.

Here’s some closely associated brain damage for you to witness:

$a = array(1,2);
reset($a); # make sure we're starting with a clean array pointer
var_dump(pos($a)); # integer, value 1, as expected
var_dump(prev($a)); # FALSE, to be expected
var_dump(next($a)); # FALSE!!

So the assertion that making one step backwards and one forward leaves you where you started is a no-go here.
Talk about common sense semantics…

And this is harmless in comparison, but still:

Note: You won’t be able to distinguish the end of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.

Oh, do I need to remind you they are at major version FIVE of their language?

Comments

  1. pcdinh
    July 20th, 2008 | 12:01 pm

    You may want to take a look here http://wiki.php.net/rfc/closures

    It has been in PHP 5.3 already, which will be available on August, 2008

Leave a reply