• home
  • forum
  • my
  • kt
  • download
  • Arrays in PHP

    Author: 2009-03-09 10:08:19 From:

    Arrays

    There are times in programming where you need to keep track of many variables at once. Maybe the current time of day, the number of items in a package or the name of a certain product. These variables may all be very similar too though, you might, for example, need to keep track of the names of all employees in a company, or the number of items inside each of a large number of packages. Arrays can be used to keep track of these multiple values from within one variable.

    Arrays are a special type of data structure in PHP. They are used to hold multiple values, in a way which allows the values held within to be re-arranged, searched or sorted. Values can also be removed or added easily. Arrays are especially useful when you’re dealing with lists of items, or collections of values that need to be sorted into ascending or descending order.

    Creating and manipulating arrays

    An array is initialised using the language construct array(), and is assigned to a PHP variable name, in exactly the same way as other scalar variables [reference scalar in previous tut]. Arrays can contain any number of values, each of which can be any of the PHP data types. Here is an example of a simple array

    $array = array(1, "two", 3.0, "four");

    This will initialise the variable $array as an array containing the values 1, “two”, 3.0 and “four”.

    An array like this is known as a Non-associative array because the values are not associated with any specific keys but are instead just numbered numerically, like so…

    An example of a simple non-associative array

    An example of a simple non-associative array

    Displaying Arrays

    Once this array has been initialised, we can check the contents of the array in certain ways

    1
    2
    3
    
    echo $array;
    print_r ($array);
    var_dump($array);

    This produces

    1
    2
    3
    
    Array
    Array ( [0] => 1 [1] => two [2] => 3 [3] => four )
    array(4) { [0]=> int(1) [1]=> string(3) "two" [2]=> float(3) [3]=> string(4) "four" }

    Echo is not built to handle complex data structures like arrays. Instead we need to turn to our old friend print_r() - but even then, we’re not getting the full picture. Var_dump() produces the most information about our array, giving us the datatype held in each position of the array.

    Associative arrays

    Note the numbers in square brackets on lines 2 and 3 in the above example. These numbers correspond to the “keys” of each item in the array. Arrays work by assigning each item a “key-value pair” by which to reference each position in the array. In the above example, the keys are generated automatically, in sequence according to the order in which the values were entered. We can over-ride this behaviour though, and specify our own keys for each value

    $array = array(4 => 1, 3 => "two", 2 => 3.0, 1 => "four");

    Here, we’ve assigned the entries in the array to keys in descending numerical order.

    Another example is an array containing a list of employee names, and their associated job titles

    Now, you might be asking, what’s the use of this feature in real code? Well, this gives me a good opportunity to introduce a powerful feature of arrays - sorting.

    Sorting Arrays

    To sort arrays, we can invoke a wide range of functions on our variable $array. The simplest of these is sort(). We’ll use a simpler array this time, to prevent confusion. All the datatypes here are strings, labelled numerically with their string equivalent. See how, in this instance, we’re still assigning each string value a key, and the keys are arranged in descending numerical order

    $array = array(4 => "one", 3 => "two", 2 => "three", 1 => "four");
    print_r($array);
    sort($array);
    print_r($array);

    This will produce the output

    Array ( [4] => one [3] => two [2] => three [1] => four )
    Array ( [0] => four [1] => one [2] => three [3] => two )

    But wait, is that not what you expected? The thing to bear in mind here is that the values we’ve assigned to the array entries are strings. And in this case, the sort() function is sorting the values in alphabetical order.

    See how in the second line, after the sort() function, the keys have been reset - we now start with the key “0″ and increment the keys for each new value. The default behaviour of arrays in PHP is to assign the value 0 to the first key, not 1 as you might expect.

    If we want to maintain the keys in our array though, so that each value is still associated with the key that we assigned it, we can use the asort() function.

    $array = array(4 => "one", 3 => "two", 2 => "three", 1 => "four");
    asort($array);
    print_r($array);

    Will produce the output

    Array ( [1] => four [4] => one [2] => three [3] => two )

    But, this might still not be what you’re looking for in a sort function. What if we wanted to sort our array not by the value of each entry, but the keys associated with each value? Well, in that case we can use the ksort() function

    $array = array(4 => "one", 3 => "two", 2 => "three", 1 => "four");
    ksort($array);
    print_r($array);

    And this produces the output

    Array ( [1] => four [2] => three [3] => two [4] => one )

    Multidimensional arrays

    Once you start delving deep into the nature of Arrays in PHP, you’ll discover a great deal of complexity hidden beneath the surface. Much of this complexity comes from the fact that arrays can potentially contain other arrays as values too. You can see how this might make things a little harder to visualise!

    Sorting Multidimensional Arrays

    Consider this example. A delivery service needs to maintain a list of addresses and names where packages are to be sent on a specific day. Along with this information, they also need to assign each delivery a priority number, to ensure that the most important deliveries arrive first.

    $customer_1 = array("name" => "Billy Bob", "address" => "1 The Street, Streetsville", "priority" => 3);
    $customer_2 = array("name" => "Jim James", "address" => "4 Avenue Road, Roadtown", "priority" => 1);
    $customer_3 = array("name" => "Henry Henriksson", "address" => "79 Pavement Lane, Paveston", "priority" => 4);
    $customer_4 = array("name" => "Alan Alansson", "address" => "55 Ocean Drive, Ocean City", "priority" => 2);
    $deliveries = array($customer_1, $customer_2, $customer_3, $customer_4);
    print_r($deliveries);

    This will produce the following output (formatted for ease of reading)

    Array (
      [0] => Array ( [name] => Billy Bob [address] => 1 The Street, Streetsville [priority] => 3 )
      [1] => Array ( [name] => Jim James [address] => 4 Avenue Road, Roadtown [priority] => 1 )
      [2] => Array ( [name] => Henry Henriksson [address] => 79 Pavement Lane, Paveston [priority] => 4 )
      [3] => Array ( [name] => Alan Alansson [address] => 55 Ocean Drive, Ocean City [priority] => 2 ) ) 
    )

    So you can see, the $deliveries array contains, as its values, other arrays, with key values 0, 1 and 2. We now have a data structure containing all the information we need to decide who gets their parcel first. But we can’t base that decision on the order of entries in the array, and we can’t apply any of the sorting mechanisms outlined in the previous tutorial because the information we need to use to decide what the ordering should be is hidden away inside the array values, and PHP doesn’t know that we wish to sort by these values on its own, so what can we do here?

    Thankfully, PHP includes a number of useful functions we can use to deal with nasty multidimensional arrays like this, and the one we’re going to use here to solve our problem is called usort()

    usort() is used to execute user-defined functions on all the values inside an array. We’ll define a function here, and call it delivery_sort()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    function delivery_sort($a, $b)
    {
        $priority_a = $a["priority"];
        $priority_b = $b["priority"];
        if ($priority_a == $priority_b) {
            return 0;
        }
        return ($priority_a < $priority_b) ? -1 : 1;
    }

    Then, we apply that function to our $delivery array by using the usort function

    usort($deliveries, "delivery_sort");
    print_r($deliveries);

    This gives us a newly ordered $deliveries array, with the highest priority array listed first

    Array (
      [0] => Array ( [name] => Jim James [address] => 4 Avenue Road, Roadtown [priority] => 1 )
      [1] => Array ( [name] => Alan Alansson [address] => 55 Ocean Drive, Ocean City [priority] => 2 )
      [2] => Array ( [name] => Billy Bob [address] => 1 The Street, Streetsville [priority] => 3 )
      [3] => Array ( [name] => Henry Henriksson [address] => 79 Pavement Lane, Paveston [priority] => 4 ) )

    Let’s take a step-by-step look at what’s happening here

    • Line 1 : the function takes as its parameters, two values $a and $b. usort() will compare each entry in the target array with each other entry using these parameters (e.g. $a = array key 0, $b = array key 1, and then $a = array key 0, $b = array key 2 and so on)
    • Lines 3, 4 : within the function, we have access to each of the $customer arrays through the usort() function, and can access the value of “priority”
    • Lines 5-8 : the important thing to note about usort is that the values returned determine how the array is to be sorted. If the value of “priority” in $a is less than “priority” in $b in our case, then we return -1. This lets usort() know that $a should be sorted lower than $b. Similary, if they are equal, we return 0, and if greater, we return 1

    discuss this topic to forum

    relation tutorial

    No information

    Category

      Ad Management (6)
      Calendars (3)
      Chat Systems (8)
      Content Management (41)
      Cookies and Sessions (12)
      Counters (15)
      Database Related (34)
      Date and Time (15)
      Development (22)
      Discussion Boards (8)
      E Commerce (8)
      Email Systems (14)
      Error Handling (8)
      File Manipulation (36)
      Flash and PHP (6)
      Form Processing (22)
      Guestbooks (12)
      Image Manipulation (26)
      Installing PHP (7)
      Introduction to PHP (25)
      Link Indexing (8)
      Mailing List Management (9)
      Miscellaneous (53)
      Networking (8)
      News Publishing (9)
      OOP (24)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (6)
      Postcards (1)
      Randomizing (14)
      Redirection (11)
      Searching (9)
      Security (29)
      Site Navigation (16)
      User Authentication (14)
      WAP and WML (7)
      Web Fetching (8)
      Web Traffic Analysis (15)
      XML and PHP (16)

    New

    Hot