Converting, sorting, etc arrays in PHP.

PHP, despite what many “purists” might say, is a powerful programming language. It’s inception has created many things which now exist on the Internet in record time – programs that used to be written in CGI, with custom libraries and horrible amounts of development time, can now be produced with less time, less Q&A, and much less effort.

This, of course, comes at a price. It can do many things, and it assumes the author to know exactly what they’re doing – that, and for the bazillion things it does offer – there are many things it does not.

For instance, I’m currently working on a “Who’s Online” system, which allows one to add friends by name, and see if they’re utilizing a certain service. This is pretty trivial, but PHP does not natively offer case-insensitive searches.

This would mean that you might have to iterate through an entire array and do string comparisons, since there’s no obviously-easy way to do an array-wide strtolower() or strtoupper(), et al.

However, rather than killing CPU cycles and memory on this, there is a somewhat-odd solution I tried, and worked – mapping the array unto another array.. and performing a function on that during the mapping. E.G:

$lowerUserConnected = array_map(‘strtolower’, $usersConnected);

This assigns the $lowerUsersConnected variable to assume the data of $usersConnected, after performing the internal strtolower() function upon it. It seems a bit awkward, but it works. Being that it keeps the keys (which are numeric), it’s possible to obtain the data from the $usersConnected array, and utilize the data in the $lowerUsersConnected array for comparison – it seems a bit costly, but certainly less than manually stepping through and converting $usersConnected by any user-written function.

Thus, it’s possible to:

$arbitrary_data = array_intersect($lowerUsersConnected, $friendsList));

and utilize the appropriate names from $usersConnected.