Home arrow PHP arrow Page 5 - Arrays

Determining Array Size and Uniqueness - PHP

Arrays offer an ideal means for storing, manipulating, sorting, and retrieving the kinds of data sets that programmers spend a lot of time working with. PHP supports the array data type. This article explains the array-based features and functions it supports. It is excerpted from the book, Beginning PHP 5 and MySQL: From Novice to Professional, by W. Jason Gilmore (Apress, 2004; ISBN: 1893115518).

  1. Arrays
  2. Outputting Arrays
  3. Testing for an array
  4. Locating Array Elements
  5. Determining Array Size and Uniqueness
  6. Other Useful Array Functions
By: Apress Publishing
Rating: starstarstarstarstar / 37
June 23, 2005

print this article



A few functions are available for determining the number of total and unique array values. I’ll introduce these functions in this section.


integer count(array input_array [, int mode])

The count() function, quite simply, returns the total number of values found in the input_array. If the optional mode parameter is enabled (set to 1), the array will be counted recursively, a feature useful when counting all elements of a multidimensional array. An example follows:

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

This returns:


You may be scratching your head at this outcome, because there appears to be only five elements in the array. 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.


array array_count_values(array input_array)

The array_count_values() function returns an array consisting of associative key/value pairs. Each key represents a value found in the input_array, and its corresponding value denoting 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);

This returns:

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

  • SORT_REGULAR: Sort items by their ASCII value. This means that B will come before a, for instance. Search the Internet for ASCII table to view a comprehensive character ordering.

  • SORT_STRING: Sort items in a fashion that might better correspond with how a human might perceive the correct order. See natsort() for further information about this matter, introduced later in this section.

Consider an example. Suppose you wanted to sort exam grades from lowest to highest:

$grades = array(42,57,98,100,100,43,78,12);

The outcome looks like this:

Array ( [0] => 12 [1] => 42 [2] => 43 [3] => 57 [4] => 78 [5] => 98 [6] => 100 [7] => 100 )

It’s important to note that key/value associations are not maintained. Consider the following example:

$states = array("OH" => "Ohio", "CA" => "California", "MD" => "Maryland");

Here’s the output:

Array ( [0] => California [1] => Maryland [2] => Ohio ) ===========================================================

To maintain these associations, use asort(), introduced later in this section.


void natsort(array target_array)

The natsort() function is intended to offer a sorting mechanism comparable to those people normally use. The PHP manual offers an excellent example of what is meant by this; Consider the following items: picture1.jpg, picture2.jpg, picture10.jpg, picture20.jpg. Sorting these items using typical algorithms results in the following ordering:


void asort(array target_array [,integer sort_flags])

The asort() function is identical to sort(), sorting the target_array in ascending order, except that the key/value correspondence is maintained. Consider an array that contains the states in the order in which they joined the Union:

$state[0] = "Delaware";
$state[1] = "Pennsylvania";
$state[2] = "New Jersey"

Sorting this array using sort() causes the associative correlation to be lost, which is probably a bad idea. Sorting using sort() and then outputting the results using print_r() results in the following:

Array ( [0] => Delaware [1] => New Jersey [2] => Pennsylvania ) ===========================================================

However, sorting with rsort() results in:

Array ( [0] => Delaware [2] => New Jersey [1] => Pennsylvania ) =======================================================

If you use the optional sort_flags parameter, the exact sorting behavior is determined by its value, as described in the sort() section.


boolean array_multisort(array array [, mixed arg [, mixed arg2...]])

The array_multisort() function can sort several arrays at once, and can sort multidimensional arrays in a number of fashions, returning TRUE on success and FALSE otherwise. It takes as input one or more arrays, each of which can be followed by flags that determine sorting behavior. There are two categories of sorting flags: order and type. Each flag is described in Table 5-1.

Table 5-1. array_multisort() Flags

SORT_ASCOrderSort in ascending order
SORT_DESCOrderSort in descending order
SORT_REGULARTypeCompare items normally
SORT_NUMERICTypeCompare items numerically
SORT_STRINGtypeCompare items as strings


integer krsort(array array [,int sort_flags])

The krsort() function operates identically to ksort(), sorting by key, except that it sorts in reverse (descending) order.


void usort(array array, callback function_name)

The usort() function offers a means for sorting an array using a user-defined comparison algorithm, embodied within a function. This is useful when you need to sort data in a fashion not offered by one of PHP’s built-in sorting functions.

The user-defined function must take as input two arguments, and must return a negative integer, zero, or a positive integer based on whether the first argument is less than, equal to, or greater than the second argument. Not surprisingly, this function must be made available to the same scope in which usort() is being called.

A particularly applicable example of usort() involves the ordering of American-format dates. Suppose that you want to sort an array of dates in ascending order:

< ->php
$dates = array('10-10-2003', '2-17-2002', '2-16-2003', '1-01-2005', '10-10-2004');
// Array ( [0] => 10-01-2002 [1] => 10-10-2003 [2] => 2-16-2003 [3] => 8-18-2002 )
// Array ( [2] => 2-16-2003 [3] => 8-18-2002 [1] => 10-01-2002 [0] => 10-10-2003 )
function DateSort($a, $b) {
   // If the dates are equal, do nothing.
   if($a == $b) return 0;
// Dissassemble dates
   list($amonth, $aday, $ayear) = explode('-',$a);
   list($bmonth, $bday, $byear) = explode('-',$b);
// Pad the month with a leading zero if leading number 
   not present
   $amonth = str_pad($amonth, 2, "0", STR_PAD_LEFT);
   $bmonth = str_pad($bmonth, 2, "0", STR_PAD_LEFT);
// Pad the day with a leading zero if leading number
   not present
   $aday = str_pad($aday, 2, "0", STR_PAD_LEFT);
   $bday = str_pad($bday, 2, "0", STR_PAD_LEFT);
// Reassemble dates
   $a = $ayear . $amonth . $aday;
   $b = $byear . $bmonth . $bday;

key that already exists in the resulting array, that key/value pair will overwrite the previously existing entry. This behavior does not hold true for numerical keys, in which case the key/value pair will be appended to the array. An example follows:

$face = array("J","Q","K","A"); 
$numbered = array("2","3","4","5","6","7","8","9");
$cards = array_merge($face, $numbered);

This returns something along the lines of the following (your results will vary because of the shuffle):

Array ( [0] => 8 [1] => 6 [2] => K [3] => Q [4] => 9 [5] => 5 
[6] => 3 [7] => 2 [8] => 7 [9] => 4 [10] => A [11] => J )


array array_merge_recursive(array input_array1, array input_array2 [, array...])

The array_merge_recursive() function operates identically to array_merge(), joining two or more arrays together to form a single, unified array. The difference between the two functions lies in the way that this function behaves when a string key located in one of the input arrays already exists within the resulting array. array_merge() will simply overwrite the preexisting key/value pair, replacing it with the one found in the current input array. array_merge_recursive() will instead merge the values together, forming a new array with the preexisting key as its name. An example follows:

$class1 = array("John" => 100, "James" => 85);
$class2 = array("Micky" => 78, "John" => 45);
$classScores = array_merge_recursive($class1, $class2); print_r($classScores);

This returns the following:

Array ( [John] => Array ( [0] => 100 [1] => 45 ) [James] => 85 [Micky] => 78 ) ===========================================================

Note that the key “John” now points to a numerically indexed array consisting of two scores.


array array_slice(array input_array, int offset [, int length])

The array_slice() function returns the section of input_array starting at the key offset, and ending at position offset + length. A positive offset value will cause the


This returns:

Array ( [0] => Alabama [1] => Alaska [2] => Arizona [3] => Arkansas ) Array ( [0] => California [1] => Connecticut )

You can use the optional parameter replacement to specify an array that will replace the target segment. An illustration follows:

$states = array("Alabama", "Alaska", "Arizona", "Arkansas", "California",
$subset = array_splice($states, 2, -1, array("New York", "Florida"));

This returns the following:

Array ( [0] => Alabama [1] => Alaska [2] => New York [3] => Florida [4] => Connecticut ) ===========================================================


array array_intersect(array input_array1, array input_array2 [, array...])

The array_intersect() function returns a key-preserved array consisting only of those values present in input_array1 that are also present in each of other the input arrays. An example follows:

$array1 = array("OH","CA","NY","HI","CT");
$array2 = array("OH","CA","HI","NY","IA");
$array3 = array("TX","MD","NE","OH","HI");
$intersection = array_intersect($array1, $array2, $array3); print_r($intersection);

This returns:

Array ( [0] => OH [3] => HI ) ===========================================================

Note that array_intersect() only considers two items to be equal if they also share the same datatype.


array array_diff_assoc(array input_array1, array input_array2 [, array...])

The function array_diff_assoc() operates identically to array_diff(),except that it also considers array keys in the comparison. Therefore only key/value pairs located in input_array1, and not appearing in any of the other input arrays, will be returned in the result array. An example follows:

$array1 = array("OH" => "Ohio", "CA" => "California", "HI" => "Hawaii");
$array2 = array("50" => "Hawaii", "CA" => "California", "OH" => "Ohio");
$array3 = array("TX" => "Texas", "MD" => "Maryland", "KS" => "Kansas");
$diff = array_diff_assoc($array1, $array2, $array3); print_r($diff);

This returns:

Array ( [HI] => Hawaii ) ===========================================================

>>> More PHP Articles          >>> More By Apress Publishing

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: