Five Cool PHP Array Functions
Out Of Date Warning
Languages change. Perspectives are different. Ideas move on. This article was published on October 21, 2009 which is more than two years ago. It may be out of date. You should verify that technical information in this article is still current before relying upon it for your own purposes.
- 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().
usort(array $array, callback $callback_function)
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.
array_pop(array &$array)
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'
?>
array_merge(array $array1 [, array $array2 [, array $... ]] )
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.
<?php
$array1 = array('apple', 'blueberry');
$array2 = array('pear', 'banana');
$array = array_merge($array1, $array2);
var_dump($array);
The output of the above code is:
[0]=>
string(5) “apple”
[1]=>
string(9) “blueberry”
[2]=>
string(4) “pear”
[3]=>
string(6) “banana”
}
array_rand(array $input [, int $num_req = 1 ])
A long time ago I needed to get a random value out of an array of quotes. The code I came up with looked something like this:
<?php
function getRandom(&amp;amp;amp;amp;$array)
{
$count = count($array);
$key = rand(0, $count);
$quote = $array[$key];
unset($array[$key]);
return $quote;
}
This function works, but it’s so much simpler to do just this:
function getRandom(&amp;amp;amp;amp;$array)
{
$key = array_rand($array);
$quote = $array[$key];
unset($array[$key]);
return $quote;
}
This does exactly the same thing while removing an extra function call that was ultimately unnecessary. While this little performance boost might not ultimately be too great, using the built-in function is much cleaner, much clearer, and much preferred.
What are your favorite array functions?
This blog entry implements The Beginner Pattern.

Write better object
oriented PHP today.
A brand new book on object oriented PHP that will leave you an object oriented master.
Learn more about the book »array_key_exists vs isset:
http://www.alternateinterior.com/2006/11/comparing-array_key_exists-with-isset.html
I often use isset() myself, since a language construct will always run faster than a function. But I think array_key_exists() is a cool function, which is why I mentioned it. :-)
Remember, this is a beginner article, and most web hosts haven’t yet upgraded to PHP 5.3.
To get only a list of unique values from an array:
array_unique($array);
However, this can be done faster like so:
array_keys(array_flip($array));
how about array_map, array_walk, array_filter and array_reduce? or it is advanced functionality and not ready for begginer?
I don’t like articles with names like “N cool stufs”(where N is any number), because it is cooles for author and as always author miss another cool things. But hey it is my opinion and article can be useful for beginners :)
I wanted to present some basic array functions that I often see duplicated in custom PHP code. That’s why I picked the five I did. Thanks for your comment!
Great Article – Here are my favorites:
array_filter – by default removes empty elements, but you can pass it a callback to filter
array_chunk – partitions an array
uasort – sorts an array and keeps they keys intact.
And also, to get the last value from an array without modifying it, i use this trick
$last = array_pop(array_values($my_array));
Don’t forget implode/explode for converting strings to arrays and vice versa. I’ve always said that those two are the duct tape and WD40 of PHP. :)
@omerida You probably know this already, but you can also grab the last element from an array without popping it using the end() function. However, it does change the internal pointer in the array (but doesn’t remove the item).
Hm. My example was stripped out :(
$fruits = array(‘apple’, ‘banana’, ‘cranberry’);
echo end($fruits); // cranberry
(copy-paste from http://ua2.php.net/end)
@robin – thanks, I didn’t know to use end() that way. I knew about those others too so my first though was to abuse them.
I’d also add that array_reverse and array_diff can be quite handy too.
My favorite is array_map in conjunction with create_function
…
$arrayOfIntegers = array_map(create_function(‘$x’, ‘return intval($x);’), $arrayOfIntegerStrings);
…
As far as array manipulation is concerned, PHP is the bee’s knees ;)
Another interesting thing about array_merge() is that it re-indexes the arrays. You can pass it just one array to have the indexes reset.
$test = array(‘first’, ‘second’, ‘third’);
unset($test[1]);
$test = array_merge($test);
‘first’ is now $test[0], ‘third’ is now $test[1].
@Oscar – end() for last element and for first? reset() – some php functions are very badly designed
@optik – functions such as end(), next(), prev() change the internal array pointer.
So current() will get the first element until any of the above functions are called, a reset() would then be required. Ideally there should be a first() function!
array_key_exists this function doesn’t operate properly, I use it tens of times .
I tested it this morning; seems to work just fine. I think you’re doing it wrong.
array_key_exists works just fine, but it will still return TRUE even if you set the value to NULL for a given index:
$foo[42] = null;
var_dump(array_key_exists($foo, 42)); //TRUE
This can be confusing if you expect NULL to “wipe out” the key/value entirely.
To really get rid of it, use unset:
unset($foo[42]);
Personally, I rarely use NULL in PHP (partially because it didn’t exist for so long) and simply use isset/unset.
I use NULL only when I need to clearly define a NULL value to be sent to a database layer at some point down the line.
@Will K, what would be the difference between first() and reset()? I don’t think there would be any. first() would need to move the internal pointer to the beginning of the array and return that element, exactly as reset() does, which is the opposite of end() which moves the internal pointer to the end of the array and returns that element.
Some this are my favorite too…
And from array_rand() function… A question came in my mind…
How does PHP pick up a random entry from set of values? – Did you know what type of method/algorithm they use in array_rand() and rand() functions.


Imagine if you could write clear, compelling code each and every time you sat down to work. You can do this. I'll show you how with The Ten Commandments of Clean Code.
Brandon Savage has been a software developer since 2003. Ever since discovering that he could use software to automate routine tasks, he's been hooked. Brandon is passionate about perfecting the art of software development.
“a callback function is a user-defined (or PHP included) function name that you pass to a function as a string.”
That is not quite accurate. See http://php.net/callback#language.types.callback for more. With PHP 5.3 and its closures, callbacks have gotten much more powerful.