Does this make ANY sense?

I’m not a computer scientist. I didn’t go to school to get letters by my name to learn how languages are built and designed, and I never wrote a compiler in my life. I’m just a fairly high end programmer who writes in high level languages, and builds large applications.
I’m certainly a big user of PHP – less so recently, but since Claimit is written in it, I’ve been getting my wheels back on it.
But, occasionally I run across design decisions that just don’t seem to make sense. Case in point, the ‘asort()‘ function. It sorts an array, in this case backwards (as opposed to sort). One would assume you’d use it like this:

$sortedArray = asort($oldarray);

Not so! This function works, does not throw any errors, but the resulting value in $sortedArray is ‘true’ (or ‘1’). The asort function returns a BOOLEAN value (successful completion of a sort??) What actually happens is the asort() function reorders an existing array. So in order to have a new version of the array sorted, or to sort the result of a function call, you use this tortured syntax:

asort($sortedArray = $oldarray);

In my case, I’m actually sorting the returned array from a function call, so we have:

asort($sortedArray = getFiles())

I understand this is a Perl-ism. That doesn’t mean it has to be perpetuated further on the masses. Ick.

About

A wandering geek. Toys, shiny things, pursuits and distractions.

View all posts by

3 thoughts on “Does this make ANY sense?

  1. Lots of sort methods work this way. Requiring the caller to copy first if that’s what they intend doesn’t increase the computational cost any, whereas if what you want is a sort in place it’d be a shame if your sort made an unwanted copy and then you had to copy it back, especially if you got an out of memory exception in the meanwhile.

  2. Oh, and by the way: *please* write:
    $array = getFiles();
    asort($array);
    assignment inside expressions is just yucky.

  3. Well, it makes some sense in that sorting in place would save memory, which could be significant with large lists. While it does create extra trouble of reassignment, it saves you the trouble of crashing in the middle.
    In addition, maybe it could allow you to do a sort on an array someone else is holding the handle to?
    Although I have heard some grumblings about PHP’s design team’s skills, so maybe it could be improved on…

Comments are closed.