[Previous] [Contents] [Next]

Basic Array Functions

In this section, we introduce selected basic PHP array library functions.

Counting elements in arrays

The count( ) function returns the number of elements in the array var:

integer count(mixed var)

The following example prints 7 as expected:

$days = array("Mon", "Tue", "Wed", "Thu",
              "Fri", "Sat", "Sun");
echo count($days);  // 7

The count( ) function works on any variable type and returns 0 when either an empty array or a variable that isn't set is examined. If there is any doubt, isset( ) and is_array( ) should be used to check the variable being considered.

Finding the maximum and minimum values in an array

The maximum and minimum values can be found from an array numbers with max( ) and min( ), respectively:

number max(array numbers)
number min(array numbers)

If an array of integers is examined, the returned result is an integer, if an array of floats is examined, min( ) and max( ) return a float:

$var = array(10, 5, 37, 42, 1, -56);
echo max($var);  // prints 42
echo min($var);  // prints -56

Both min( ) and max( ) can also be called with a list of integer or float arguments:

number max(number arg1, number arg2, number arg3, ...)
number min(number arg1, number arg2, number arg3, ...)

Both max( ) and min( ) work with strings or arrays of strings, but the results may not always be as expected.

[Previous] [Contents] [Next]