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. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access