PHP
  Home arrow PHP arrow Page 5 - Arrays
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Arrays
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 36
    2005-06-23


    Table of Contents:
  • Arrays
  • Outputting Arrays
  • Testing for an array
  • Locating Array Elements
  • Determining Array Size and Uniqueness
  • Other Useful Array Functions

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Arrays - Determining Array Size and Uniqueness
    ( Page 5 of 6 )

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

    count()

    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:

    ===========================================================
    6
    ===========================================================

    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_count_values()

    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);
    print_r($stateFrequency);

    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);
    sort($grades);
    print_r($grades);

    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");
    sort($states);
    print_r($states);

    Here’s the output:

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

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

    natsort()

    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:

    asort()

    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.

    array_multisort()

    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

    FLAG TYPE PURPOSE
    SORT_ASC Order Sort in ascending order
    SORT_DESC Order Sort in descending order
    SORT_REGULAR Type Compare items normally
    SORT_NUMERIC Type Compare items numerically
    SORT_STRING type Compare items as strings

    krsort()

    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.

    usort()

    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');
    sort($dates);
    // Array ( [0] => 10-01-2002 [1] => 10-10-2003 [2] => 2-16-2003 [3] => 8-18-2002 )
    natsort($dates);
    // 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);
    shuffle($cards);
    print_r($cards);

    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_merge_recursive()

    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_slice()

    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

    print_r($states);
    print_r($subset);

    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",
    "Connecticut");
    $subset = array_splice($states, 2, -1, array("New York", "Florida"));
    print_r($states);

    This returns the following:

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

    array_intersect()

    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_diff_assoc()

    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
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    Stay green...Green IT