Using Array Functions

You’ve already seen the list and each functions, but PHP comes with numerous other functions for handling arrays. The full list is at However, some of these functions are so fundamental that it’s worth taking the time to look at them here.


Arrays and variables share the same namespace. This means that you cannot have a string variable called $fred and an array also called $fred. If you’re in doubt and your code needs to check whether a variable is an array, you can use the is_array function like this:

echo (is_array($fred)) ? "Is an array" : "Is not an array";

Note that if $fred has not yet been assigned a value, an “Undefined variable” message will be generated.


Although the each function and loop structure are excellent ways to walk through an array’s contents, sometimes you need to know exactly how many elements there are in your array, particularly if you will be referencing them directly. To count all the elements in the top level of an array, use a command such as the following:

echo count($fred);

Should you wish to know how many elements there are altogether in a multidimensional array, you can use a statement such as:

echo count($fred, 1);

The second parameter is optional and sets the mode to use. It should be either a 0 to limit counting to only the top level, or 1 to force recursive counting of all subarray elements, too.


Sorting is so common that PHP provides a built-in ...

Get Learning PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.