O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 http://tinyurl.com/phparrayfuncs. However, some of these functions are so fundamental that it’s worth taking the time to look at them here.

is_array

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.

count

Although the each function and the foreach...as 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 0 to limit counting to only the top level, or 1 to force recursive counting of all subarray elements too.

sort

Sorting is so common that PHP provides a built-in function for this purpose. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required