Does this make ANY sense?

29 08 2005

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.

Advertisements

Actions

Information

3 responses

30 08 2005
phi

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.

30 08 2005
phi

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

30 08 2005
blk

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…




%d bloggers like this: