Searching...
Tuesday 9 July 2013

Determining Array Size and Uniqueness


A few functions (more about functions in PHP) are available in PHP for determining the number of total and unique array (what is an array) values. These functions are introduced in this section.

Determining the Size of an Array

The count() function returns the total number of values found in an array. Its prototype is as follows:

integer count(array array [, int mode])

If the optional mode parameter is enabled ( or you can say- set to 1), the array will be counted recursively, a feature useful when counting all the elements of a multidimensional array. The first example counts the total number of vegetables found in the $garden array:

$garden = array("cabbage", "peppers", "turnips", "carrots");
echo count($garden);

This returns the following:

4

The next example counts both the scalar values and array values found in $locations identifier:

$locations = array("Italy", "Amsterdam", array("Boston","Des Moines"), "Miami");
echo count($locations, 1);

This returns the following:

6

You may be scratching your head at this outcome because there appears to be only five elements in the array. It’s because the array entity holding Boston and Des Moines is counted as an item, just as its contents are.

Note: The sizeof() function is an alias of count(). It is functionally identical.

Counting Array Value Frequency

The array_count_values() function returns an array consisting of associative key/value pairs. Its prototype follows:

array array_count_values(array array)

Each key represents a value found in the input_array, and its corresponding value denotes the frequency of that key’s appearance (as a value) in the input_array. An example follows:

$states = array("Ohio", "Iowa", "Arizona", "Iowa", "Ohio");
$stateFrequency = array_count_values($states);
print_r($stateFrequency);

This returns the following:

Array ( [Ohio] => 2 [Iowa] => 2 [Arizona] => 1 )

Determining Unique Array Values

The array_unique() function removes all duplicate values found in an array, returning an array (more about arrays in PHP) consisting of solely unique values. Its prototype follows:

array array_unique(array array [, int sort_flags = SORT_STRING])

An example follows:

$states = array("Ohio", "Iowa", "Arizona", "Iowa", "Ohio");
$uniqueStates = array_unique($states);
print_r($uniqueStates);

This returns the following:

Array ( [0] => Ohio [1] => Iowa [2] => Arizona )

The optional sort_flags parameter (added in PHP 5.2.9) determines how the array values are sorted. By default, they will be sorted as strings (what is string data type); however, you also have the option of sorting them numerically (SORT_NUMERIC), using PHP’s default sorting methodology (SORT_REGULAR), or according to a locale (SORT_LOCALE_STRING).

0 comments:

Post a Comment

 
Back to top!