Arrays in PHP

PHP allows developers to use Arrays for storing more complex data.  Arrays store similar data in a convenient block.  This will reduce the amount of variables you need to create.  Arrays can also be manipulated through a variety of functions.

Index and Associate Arrays

An array is a programming technique used to store multiple pieces of information with a similar theme.  You can think of this in terms of house street numbers.  All the houses are on Acacia Avenue can be identified by their house numbers.  If you know you are talking about Acacia Avenue you can refer to a specific house as just number 6, number 12 etc.  In array terminology the house numbering is known as the index (or key) and each house an element.  Our street analogy falls down slightly in that arrays are zero based ie the first element in the array is indexed as [0].

In PHP there are two types of arrays indexed and associate.  An indexed array is indexed by number (starting at 0) whereas an associate array is indexed with strings.  In the street analogy we could refer to the houses by house name ie ‘The Manor’, ‘Valley View’.  The house names would all need to be unique.

With an associate array you can extract values as follows:

$acaciaAvenue['valleyView'];

We have already seen an associate array in the shape of the $_POST superglobal variable.  That is all the values submitted from a HTML form with a method of ‘post’ are in the associate array $_POST.  They are then referenced by name ie $_POST[‘surname’] references the HTML form element named ‘surname’.

Thus the square brackets are used to access the different value in the array.  With an indexed array the third value in the array is referenced as follows:

$myarray[2]

Populating Arrays

Arrays are created as like any other variable but because of the multiple values they store, they need to be populated using special syntax.  To create an array you can populate the array item by item:

$myarray[] = 'Johnny';
$myarray[] = 'Stephen';
$myarray[] = 'Andy';
$myarray[] = 'Mike';

Alternatively an array function can be used ie:

$myarray = array('Johnny', 'Stephen', 'Andy', 'Mike');

The above produces an index array with keys automatically assigned but keys they can be explicitly declared:

$myarray = array(0=>'Johnny', 1=>'Stephen', 2=>'Andy', 3=>'Mike');

This is also the case with associate arrays.

$myarray = array('Guitar' => 'Johnny', 'Vocals'=> 'Stephen', 'Bass' => 'Andy', 'Drums' => 'Mike');

Values could then be extracted using the associate key as follows:

$myarray['Guitar'];//outputs Johnny

Diversion: Know the band? The Smiths of course

Arrays can contain a mix of string, numeric and Boolean values ie:

$variousarray = array("cat", 123, 1.243, true);

Multidimensional Arrays

Arrays can also be multidimensional ie an array item can be another array.  This is called a two dimensional array.

<?php
$cart = array(array("Baked Beans", 4, 51), array("Apples", 14, 0.35), array("Bananas", 1, 0.49));
echo $cart[0][0];
//outputs “Baked Beans”
?>

Access values in a two dimensional array with double square brackets ie $cart[0][0] as above.

Outputting Array Values with print_r()

For debugging purposes the print_r() function can be a useful way to dump the values of an array to the screen.

print_r($myarray);

To output any single array value just requires the right key/index in the square brackets.

When printing arrays ensure you place them in curly brackets to prevent errors.  ie use:

echo "The current value is {$myarray[5]}";

Looping Around an Array with foreach

However, more often than not you want all the values from the array.  To access every array element use a foreach loop, the syntax for which is:

foreach ($myarray as $myvalue){
//execute code
}

Thus to echo all the values from an array we would do:

foreach($myarray as $myvalues){
echo "Band member: $myvalues <br>";
}

We can also use foreach to output the key value whether index or associate using:

foreach ($myarray as $key => $myvalue){
//execute code
}

Tip:  In the above example think of the => as an arrow so you are extracting the key for a value.

A fuller example been:

foreach($myarray3 as $key => $myvalues){
echo "On $key we have $myvalues <br>";
}

Array Functions

There are a number of functions that can be used with arrays.  For a full list visit the ‘php.net’ website.

array_pop()

The array_pop() is used to remove the last element from an array.

$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
print “Popped fruit is ($fruit)”;
//outputs 
Array ( [0] => orange [1] => banana [2] => apple ) 
//Popped fruit is (raspberry)
[//php]


<h3>array_push()</h3>
<p>The <span class="codeintext">array_push()</span> is used to add a new  element at the end of an array.</p>

1
$stack = array("orange", "banana");
print_r($stack);
echo "<br>";
array_push($stack, "apple", "raspberry");
print_r($stack);//outputs
Array ( [0] => orange [1] => banana ) 
Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry )

count()

The count() function returns the number of elements in the array.

$months = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
echo count($months); // outputs 12

array_count_values()

The array_count_values() function returns the number of instances of a particular value in an array.

$foodarray = array("Chips", "Cheese", "Apples", "Bananas", "Chips", "Cake", "Chips");
print_r (array_count_values($foodarray)); 
// outputs 
Array ( [Chips] => 3 [Cheese] => 1 [Apples] => 1 [Bananas] => 1 [Cake] => 1 )


implode()

The implode() function is used to turn an array into a string.  It accepts an array value and a separator.

$foodarray = array("Chips", "Cheese", "Apples", "Bananas", "Chips", "Cake", "Chips");
print "I love to eat " .implode(" and ", $foodarray) . "."
//outputs
//I love to eat Chips and Cheese and Apples and Bananas and Chips and Cake and Chips.

Note:  Remember in the above example the ‘.’ is been used as a concatenation character.


explode()

The explode() function does the reverse of implode() and it is used to turn a string into an array.  It accepts a string and separator.

$foodstring = "I love to eat chips";
$foodarray = explode(" ", $foodstring);
print_r($foodarray);
//outputs
//Array ( [0] => I [1] => love [2] => to [3] => eat [4] => chips )

range()

The range() function can be used to create an array from a range of sequential numbers ie:

$percent = range(1, 100);

The above creates an array $percent with 100 elements equivalent to:

$percent [0] = 1;
$percent [1] = 2;
$percent [2] = 3;
$percent [3] = 4;
… etc etc …
$percent [96] = 97;
$percent [97] = 98;
$percent [98] = 99;
$percent [99] = 100;

Leave a Reply

*