QRdvark.com

Introduction To Arrays

Introduction To Arrays

by Kevin Waterson

Contents

  1. What is an array?
  2. When do I use an array
  3. Can an Array contain other Arrays?
  4. Creating an arrray
  5. Count the members of an Array
  6. Get the Size of an Array
  7. Accessing Array Values
  8. Array Keys and Indexes
  9. Sorting an Array
  10. Add an Element to Array
  11. Delete and Array Element
  12. Multi Dimensional Arrays

What is an array?

An array is PHP is an ordered map of keys and values. A key may be defined as an index, and a value may be defined as a variable. If this is not clear, we hope that it will become clearer as we progress. Lets begin with an empty array. That is, an array with no keys or values.


<?php

 
/*** create an empty array ***/
 
$array = array();

?>

The above script will not do much. In fact, it will do less than not much, as there is no output. However we can see we have created a valiable named $array that is now an empty array. PHP provides a function to check to see if a varible is indeed and array or not. The is_array() function takes a varible as its only arguement and returns boolean TRUE if the variable is an array, or FALSE if the varable is not an array. Lets check it on the the empty array we created above.


<?php
 
/*** create an empty array ***/
 
$array = array();

 
/*** check if $array is and array ***/
 
if(is_array($array))
 {
        
/*** if it is an array ***/
        
echo 'Variable is an array';
 }
 else
 {
        
/*** if it is not an array ***/
        
echo 'Variable is not an array';
 }

?>

Obviously the script above will output
Variable is an array
because the is_array function has correctly detirmined that the variable is an array.

When do I use an array?

Arrays can be used in many places in PHP scripts. For functions that need to return mulitple values, for the transportation of multiple values to functions and for gathering data from database results. The PHP super globals uses arrays to keep track of many variables within PHP itself.

Can an array contain other arrays?

Yes! This is called a multi-dimensional array and this will be covered in the section on Multi-dimensional Arrays.

Creating an array

As mentioned above an array is map of key (index) and value pairs. Each key is assigned a value. The value can be in the form of variables or arrays or objects, but for now, lets look at a simple array of animals.

<?php

  
/*** create an array ***/
  
$animals = array('dingo''wombat''Steve Irwin''playpus''emu');

?>

Above we see a simple collection of Australian animals, seperated by comma's. Each of the animal value is a "member" of the array. This is the simplest form of array. Arrays come in two basic types, numeric and associative. Numeric arrays use numbers for the index of each value, and Associative arrays use strings, its that simple.

In the above array, we have not specified any keys (indexes). If no key is specified, PHP will automatically assign a numeric value to the key, thus creating a numeric array. It should be remember that the count of the key numbers begins at zero(0). Now that we have the array, we need to be able to access the values within. Lets see how this array looks by using the PHP print_r() function. The print_r() function outputs human-readable information about a variable and is an excellent tool for quickly debugging or viewing array contents.


<?php

 
/*** create an array ***/
 
$animals = array('dingo''wombat''Steve Irwin''playpus''emu');

 
/*** dump the array contents ***/
 
print_r$animals );
 
?> 
Array
(
    [0] => dingo
    [1] => wombat
    [2] => Steve Irwin
    [3] => playpus
    [4] => emu
)

The above array information displays the key/value pairs of the array clearly. This same array could have been created like this:


<?php

  
/*** create an array ***/
  
$animals = array(
        
0=>'dingo',
        
1=>'wombat',
        
2=>'Steve Irwin',
        
3=>'playpus',
        
4=>'emu',
        
'goanna',
        
21=>'wallaby',
        );

 
/*** dump the array contents ***/
 
print_r$animals );

?> 

The output of this array shows much the same as the previous array with a few additions. Two extra array members have been added on the end of the array. The first with no key specified and the last members key has jumped to 21. The output of print_r() now looks like this:

Array
(
    [0] => dingo
    [1] => wombat
    [2] => Steve Irwin
    [3] => playpus
    [4] => emu
    [5] => goanna
    [21] => wallaby
)

If no array key is specified when the array is created, PHP internally assigns in the next highest number. Array keys may also be specified as any number as with the wallaby. If another array member were added onto the end of the array without specifying and index number, what value would PHP assign to it?

An array key can also be a string. This means we can create meaningful key=>value pairs. An array with strings for indexes is called an associative array.


<?php

  
/*** create an array ***/
  
$animals = array(
        
'ernie'=>'dingo',
        
'wally'=>'wombat',
        
'rat bag'=>'Steve Irwin',
        
'playto'=>'platypus',
        
'marty'=>'emu'
        
);

 
/*** dump the array contents ***/
 
print_r$animals );

?> 

The array keys have been used in this instance to give each of the animals names. The output of print_r() now shows the key=>value pairs as they were created.

Array
(
    [ernie] => dingo
    [wally] => wombat
    [rat bag] => Steve Irwin
    [playto] => platypus
    [marty] => emu
)

It should be noted that whilst using strings as keys shows descriptive names, numerical keys are faster and this could be an issue with very large data arrays.

Count and Size Of an Array

PHP provides two methods of counting the members in an array.

  • count()
  • sizeof()

The sizeof() function is an alias of the count function(). This means it is exactly the same in every way, except its name. The choice of which one you use is yours as some people will want to "count" the members in an array, or others may wish to know the "sizeof" the array. Here we will show each one in action.


<?php

 
/*** create an array ***/
 
$animals = array( 'dingo''wombat''Steve Irwin''playpus''emu' );

 
/*** show the count of members in the array ***/
 
echo count$animals );

 echo 
'<br />';

 
/*** show the size of the array ***/
 
echo sizeof$animals );

?>

Each of the above functions will return 5. It should be noted that arrays begin counting zero and that the last index of the above array will be 4. Note also that the count() and sizeof() functions need to loop over the array which attracts a memory penalty and should be used sparingly.

Accessing Array Values

PHP allows direct access to array values by specifying the array name and the key. This may sound odd, so lets have a look.

<?php

  
/*** create an array ***/
  
$animals = array('dingo''wombat''Steve Irwin''playpus''emu');

  
/*** show the first member of the array ***/
  
echo $animals[1];

?>

Recall in the previous section we stated that arrays begin there numerical index at zero, unless otherwise declared. So, when we use array name, followed by square brackets which contain the key (index) of the array member we wish to use, in this instance the array index of 1 (one) has been used within the array index operators [] and the result is that the value is output. The value of the array member with the index (key) of 1 (one) is "wombat".

With the this in mind, lets try to access an array index (key) that does not exist..

<?php

  
/*** turn on error reporting ***/
  
error_reporting(E_ALL);

  
/*** create an array ***/
  
$animals = array('dingo''wombat''Steve Irwin''playpus''emu');

  
/*** show the eighth member of the array ***/
  
echo $animals[8];

?>

By making sure error reporting is on, we can see when we try to access an array key (index) beyond the size of the array, a Notice is generated

Notice: Undefined offset: 8 in /www/html/array.php on line 10

The above access method is fine if we wish to only see a single value with an array, but more often we will wish to see all the values and/or perform an operation on the value or keys(indexes) within. To achieve this we need to loop, or iterate over the array and output the value for each array key.

PHP provides several ways of achieving this using:

  • for
  • while
  • foreach
  • Iterators
  • Each of the above methods allows us to traverse an array, lets look at them in action beginning with for.

    For


    <?php

     
    /*** create an array ***/
     
    $animals = array( 'dingo''wombat''Steve Irwin''playpus''emu' );

     
    /*** get the size of the array ***/
     
    $size sizeof$animals );

     
    /*** loop over the array ***/
     
    for( $i=0$i<$size$i++ )
     {
            echo 
    $animals[$i].'<br />';
     }

    ?>

    While


    <?php

     
    /*** create an array ***/
     
    $animals = array( 'dingo''wombat''Steve Irwin''playpus''emu' );

     
    /*** get the size of the array ***/
     
    $size sizeof$animals );

     
    /*** set a counter ***/
     
    $i 0;

     
    /*** loop over the array ***/
     
    while( $i $size )
     {
            echo 
    $animals[$i].'<br />';
            
    $i++;
     }

    ?>

    The while loop expands on the compact form of the for loop. In the while loop the counter is set before the loop begins and is incremented after the output. The iteration will continue until the condition $i < $size is met. It is important to remember to increment the counter or the condition in the while loop $i < $size will never be met and an infinite loop will result, ie: the it will keep looping forever. What might be better than setting a counter is a function that would only iterate over each member of the array.

    foreach


    <?php

     
    /*** create an array ***/
     
    $animals = array( 'dingo''wombat''Steve Irwin''playpus''emu' );

     
    /*** loop over the array ***/
     
    foreach( $animals as $animal )
     {
            echo 
    $animal.'<br />';
     }

    ?>

    This method of looping over the array is probably the most common used with PHP. What has happend is that the the loop has accessed each member of the array and assigned it to the variable $nimals. This done "for each" member of the array. There is no need to set the size variable as PHP already knows how big it is. There is also no need to set a counter to increment the array key either, although the keys can be seen as we will see in the next section.

    A benifit of not having to check the size of the array is the small saving on memory. A small warning on using count() and sizeof(). In the scripts above, the count() or sizeof() the array was calculated before the array was traversed. Having count() or sizeof() inside the loop means that PHP must calculate the size on each loop, thus incurring a performance penalty. This example shows what NOT to do.


    <?php

     
    /*** create an array ***/
     
    $animals = array( 'dingo''wombat''Steve Irwin''playpus''emu' );

     
    /*** set a counter ***/
     
    $i=0;

     
    /*** DO NOT DO THIS ***/
     
    while ( $i sizeof$animals ) )
     {
            echo 
    $animals[$i].'<br />';
            
    $i++;
     }
    ?>

    Iterators

    It is beyond the scope of this tutorial to deal with SPL and iterators. Iterators provide standard interface for iterating over aggregate structures and provide many benifits. For further information on iterators the QRdvark tutorial can be found at https://QRdvark.com/tutorials/Introduction-to-SPL.html and is recommended reading

    Array Keys and Indexes

    Up to this point the arrays that have been accessed have echo'ed the value. The array key or index has only be used as an identifier for the value. Quite often, when traversing an array, you will need to access the array key itself, along with the value. These key=>value pairs are most common when accessing database results. A database result set is an array of key=> pairs with the database table column name as the key. This means the array is an associative array. Lets re-work the animals array a little to demonstrate.


    <?php

     
    /*** create an associative array ***/
     
    $animals = array( 
        
    'dingo'=>'australian',
        
    'wombat'=>'australian',
        
    'Steve Irwin'=>'australian',
        
    'platypus'=>'australian',
        
    'kiwi'=>'new zealand',
        
    'emu'=>'australian'
        
    );

     
    /*** loop over the array ***/
     
    foreach ( $animals as $key=>$animal )
     {
            
    /*** check the value ***/
            
    if( $animal != 'australian' )
            {
                    
    /*** echo the key ***/
                    
    echo $key;
            }
     }
    ?>

    In the script above, an associative array has been created with the animal names used as keys, and the land they are native to as the values. This information can be used as we loop over the array to find specific data, in this instance, any animal that is not 'australian'. The $key and $value are assign with the => operator.

    Sorting an Array

    PHP contains many different ways of sorting arrays. Array can be sorted by key or by value. The order can be natural of reverse or even case sensitive. Here are a few methods of sorting with various functions.

    Natural Sort

    The PHP sort() function will sort an array by case.


    <?php

      
    /*** create an array ***/
      
    $animals = array(
            
    'ernie'=>'dingo',
            
    'wally'=>'wombat',
            
    'rat bag'=>'Steve Irwin',
            
    'playto'=>'platypus',
            
    'marty'=>'emu'
            
    );

     
    /*** sort the array ***/
     
    sort$animals );

     
    /*** loop over the array ***/
     
    foreach( $animals as $key=>$animal )
     {
            echo 
    $key.' - '.$animal.'<br />';
     }

    ?> 

    The above sorting method has used the sort() function to arrange the array values in order. Here is the output.

    0 - Steve Irwin
    1 - dingo
    2 - emu
    3 - platypus
    4 - wombat

    The first thing that is plainly obvious is that the array keys have been removed and a numerical index has replaced it. The values themselves have been arranged in alphabetical order with upper case strings having a higher index. To maintain the array keys, the asort() function is provided as a compliment to this function.

    Sort by Key

    PHP also allows you to sort the array by its index, instead of by the value. The function for this is ksort.


    <?php

      
    /*** create an array ***/
      
    $animals = array(
            
    'ernie'=>'dingo',
            
    'wally'=>'wombat',
            
    'rat bag'=>'Steve Irwin',
            
    'playto'=>'platypus',
            
    'marty'=>'emu'
            
    );

     
    /*** sort the array ***/
     
    ksort$animals );

     
    /*** loop over the array ***/
     
    foreach( $animals as $key=>$animal )
     {
            echo 
    $key.' - '.$animal.'<br />';
     }

    ?>

    Now the array has been sorted by the value of the keys. This function also works on numberical indexes if they are out of order, perhaps database results or other. The output looks like this:

    ernie - dingo
    marty - emu
    playto - platypus
    rat bag - Steve Irwin
    wally - wombat

    Reverse Sort

    Arrays may be sorted in reverse order by key or by value. The reverse sorting compliments to the above sort() and ksort() functions are rsort() and krsort().


    <?php

      
    /*** create an array ***/
      
    $animals = array(
            
    'ernie'=>'dingo',
            
    'wally'=>'wombat',
            
    'rat bag'=>'Steve Irwin',
            
    'playto'=>'platypus',
            
    'marty'=>'emu'
            
    );

     
    /*** reverse sort the array ***/
     
    krsort$animals );

     
    /*** loop over the array ***/
     
    foreach( $animals as $key=>$animal )
     {
            echo 
    $key.' - '.$animal.'<br />';
     }

    ?>

    The above script has sorted the array by key in reverse order. The output is like this.

    wally - wombat
    rat bag - Steve Irwin
    playto - platypus
    marty - emu
    ernie - dingo

    Random Sort

    PHP provides the ability to randomize, or shuffle an array, much like suffling a deck of cards. The function for this is shuffle() and works as we saw for previous sorting functions.


    <?php

      
    /*** create an array ***/
      
    $animals = array(
            
    'ernie'=>'dingo',
            
    'wally'=>'wombat',
            
    'rat bag'=>'Steve Irwin',
            
    'playto'=>'platypus',
            
    'marty'=>'emu'
            
    );

     
    /*** sort the array ***/
     
    shuffle$animals );

     
    /*** loop over the array ***/
     
    foreach( $animals as $key=>$animal )
     {
            echo 
    $key.' - '.$animal.'<br />';
     }

    ?>

    When accessing this script several times, note that the array keys have been changed to a numerical index beginning at zero. The values however are randomly ordered.

    Add an Element To an Array

    If we have an existing array, an new array member, or multiple members, may be added, or "pushed" onto the end of the array. The function for this is array_push().


    <?php

      
    /*** create an array ***/
      
    $animals = array(
            
    'ernie'=>'dingo',
            
    'wally'=>'wombat',
            
    'rat bag'=>'Steve Irwin',
            
    'playto'=>'platypus',
            
    'marty'=>'emu'
            
    );

     
    /*** push new members onto the array ***/
     
    array_push$animals'wallaby''stingray' );

     
    /*** loop over the array ***/
     
    foreach( $animals as $key=>$animal )
     {
            echo 
    $key.' - '.$animal.'<br />';
     }

    ?> 

    The results of this show that the existing members of the array have maintained their indexes, the new additions to the array have begun numerical indexes as shown below.

    ernie - dingo
    wally - wombat
    rat bag - Steve Irwin
    playto - platypus
    marty - emu
    0 - wallaby
    1 - stingray

    There exists a second method creating an array member. By directly specifying the new array value.


    <?php

      
    /*** create an array ***/
      
    $animals = array(
            
    'ernie'=>'dingo',
            
    'wally'=>'wombat',
            
    'rat bag'=>'Steve Irwin',
            
    'playto'=>'platypus',
            
    'marty'=>'emu'
            
    );

     
    /*** push new members onto the array ***/
     
    $animals[] = 'wallaby';
     
    $animals[] = 'stingray';

     
    /*** loop over the array ***/
     
    foreach( $animals as $key=>$animal )
     {
            echo 
    $key.' - '.$animal.'<br />';
     }
    ?>

    The above script will produce the same results as the previous script. This method is preferred over the first because it reduces overhead by not having an extra function call. This method also ads the benifit of allowing us to create function to overcome the the issue with array_push() that adds numerical keys. This method of directly assigning values allows us to specify a key also.


    <?php

      
    /*** create an array ***/
      
    $animals = array(
            
    'ernie'=>'dingo',
            
    'wally'=>'wombat',
            
    'rat bag'=>'Steve Irwin',
            
    'playto'=>'platypus',
            
    'marty'=>'emu'
            
    );

     
    /*** push new members onto the array ***/
     
    $animals['wallace'] = 'wallaby';
     
    $animals['barbie'] = 'stingray';

     
    /*** loop over the array ***/
     
    foreach( $animals as $key=>$animal )
     {
            echo 
    $key.' - '.$animal.'<br />';
     }
    ?>

    Now we see a change in the array indexes. We have been able to name the keys and the values which makes an improvement on functionality and performance over array_push().

    ernie - dingo
    wally - wombat
    rat bag - Steve Irwin
    playto - platypus
    marty - emu
    wallace - wallaby
    barbie - stingray

    Delete an Array Element

    Deleting an array element is much the same us unsetting a variable, and indeed, the same function, unset(), is used.


    <?php

      
    /*** create an array ***/
      
    $animals = array(
            
    'ernie'=>'dingo',
            
    'wally'=>'wombat',
            
    'rat bag'=>'Steve Irwin',
            
    'playto'=>'platypus',
            
    'marty'=>'emu'
            
    );

     
    /*** delete an array element ***/
     
    unset( $animals['rat bag'] );

     
    /*** loop over the array ***/
     
    foreach( $animals as $key=>$animal )
     {
            echo 
    $key.' - '.$animal.'<br />';
     }

    ?> 

    When we loop over the array this time we see the array member with the key 'rat bag' has been removed.

    ernie - dingo
    wally - wombat
    playto - platypus
    marty - emu

    PHP provides a method to "pop" the last member of the array off the stack. The array_pop() function has the single task of this and cannot be used to delete other array members, only the last one.


    <?php

      
    /*** create an array ***/
      
    $animals = array(
            
    'ernie'=>'dingo',
            
    'wally'=>'wombat',
            
    'rat bag'=>'Steve Irwin',
            
    'playto'=>'platypus',
            
    'marty'=>'emu'
            
    );

     
    /*** delete the last array element ***/
     
    array_pop$animals );

     
    /*** loop over the array ***/
     
    foreach( $animals as $key=>$animal )
     {
            echo 
    $key.' - '.$animal.'<br />';
     }

    ?>

    Now we see the array is minus the last member as shown here.

    ernie - dingo
    wally - wombat
    rat bag - Steve Irwin
    playto - platypus

    Multi Dimension Arrays

    A multi-dimensional array is an array of arrays. This means each value of an array can be another array. An array key cannot be an array. An array may contain a mixture of string values and array values.


    <?php

     
    /*** create a multi dimensional array ***/
     
    $cart = array(
            array(
    'item_id'=>12'item_name'=>'book''item_price'=>44),
            array(
    'item_id'=>23'item_name'=>'book''item_price'=>23.33),
            array(
    'item_id'=>11'item_name'=>'book''item_price'=>32.40),
            );

     
    /*** loop over the array ***/
     
    foreach( $cart as $item )
     {
            echo 
    $item['item_id'].'-'.$item['item_name'].'-'.$item['item_price'].'<br />';
     }

    ?>

    The above code shows the creation of a two dimensional array of items from an imaginary book store. Each element of the cart array is itself an array. If one of these were an array, it would be referred to as a three dimensional array.

    12-book-44
    23-book-23.33
    11-book-32.4

    Looping over the array is much the same as looping over a single dimensional array. During the iteration over the array the second level array members are accessed by their keys. There are many functions for sorting and working with multi-dimensional arrays, however it is beyond the scope if this introduction to work through them here.