- Avoiding Notices: When to Use isset() and empty()
- Configuring PHP: Essential INI Settings
- Accessing Databases with PDO: A Primer
- To The New PHP Programmers…
- How To Write A Function In PHP
- Five Cool PHP Array Functions
- Micro Optimizations That Don’t Matter
- Adapting The Joel Test To Web Development
- Exceptional PHP: Introduction to Exceptions
- Suhosin: The Invisible Hand Of PHP
- Why You Should Replace ENUM With Something Else
Time and time again, I come across code that contains a variety of array-handling functions that too often duplicate the work that the PHP core team has done to develop built-in array functions. Since the built-in functions are inherently faster, trying to reimplement them in PHP will inevitably be a performance problem.
Here are five of my favorite array functions, along with their signatures and what they do.
array_key_exists(mixed $key, array $array)
Anyone who has ever had to search an array to see if a key existed can certainly make use of this function. Many times I simply use isset($array[‘key’]) as a replacement, but for small arrays (or to be explicit about what you’re doing) you should learn to use this function. There’s never a reason to duplicate this function. If you want to check the array to see if a particular value exists, use in_array().
PHP offers a whole list of array sorting functions. This extensive list provides a function for almost every occasion. But what about the times you want to sort an array and have special needs? usort() comes in handy, because it lets you define a user function (one you write) as the sorting function, and call a built-in PHP function to actually do the sorting.
For those that don’t know, a callback function is a user-defined (or PHP included) function name that you pass to a function as a string. This callback is executed by the function you call. In this case, usort() will pass the array as the single argument to the function you define.
This is a cool function. If you’ve ever had a need to get the last element off an array, this is the way to do it. I’ve seen this code replicated a hundred times, but array_pop() is fast, efficient and built-in.
This function takes an array as the argument, and then finds the very last element and pops it off the end. Note that this changes the original array, because the array is passed by reference to the array_pop() function.
<?php $array = array('apple', 'raspberry', 'banana'); $fruit = array_pop($array); echo $fruit; // Outputs 'banana' echo count($array); // Outputs '2' ?>
Combining two arrays can be difficult but this built-in PHP function does a fabulous job of making it easy. This function takes a number of arrays and returns one big array containing all of their keys and values. It’s worth noting that if two arrays contain the same key as a string, the last array combined into the master array will be the value that is returned. Numerical keys are not affected.