PHP Array…

Arrays

In this lesson of the PHP tutorial, you will learn… 

  1. To work with indexed arrays.
  2. To work with associative arrays.
  3. To work with two-dimensional arrays.
  4. To work with array-manipulation functions.

Up to this point, we have dealt only with variables that store single values, called scalar variables. In this lesson, we will be covering arrays. Arrays are variables that store sets of values.

Indexed Arrays

Indexed arrays are similar to tables with a single column. An indexed array can contain zero or more elements. In PHP, like in many programming languages, the first element of an array is in the “zeroeth” position. An array with no elements has a zero length.

Initializing Arrays

Arrays are initialized with the array() function, which can take a list of comma-delimited values that become the elements in the new array. The following lines of code initializes a zero-length array and then adds four elements to the array.

Syntax
$Beatles = array();
$Beatles[0] = 'John';
$Beatles[1] = 'Paul';
$Beatles[2] = 'George';
$Beatles[3] = 'Ringo';

The first line above is actually optional as the second line will create the array if one does not already exist. However, it is a better coding practice to explicitly initialize the array. The $Beatles array could also be created in a single line as follows.

Syntax
$Beatles = array('John','Paul','George','Ringo');

Appending to an Array

If you know how many elements are in an array, you can append to the array by specifying the index. For example, you could append to the $Beatles array shown above as follows:

Syntax
$Beatles[5] = 'Nat';

However, sometimes you don’t know how many elements are in an array. Although you can easily figure this out, doing so requires an extra step. PHP provides an easy way of appending to an array of any length. Simply leave out the index.

Syntax
$Beatles[] = 'Nat';

Reading from Arrays

Reading from arrays is just a matter of pointing to a specific index or key.

Syntax
echo $Beatles[2]; //outputs George to the browser

Looping through Arrays

The following code will loop through the entire $Beatles array outputting each element to the browser.

Syntax
foreach ($Beatles as $Beatle)
{
 echo "$Beatle<br>";
}

The above code snippets are combined in the following example.

Code Sample: Arrays/Demos/IndexedArrays.php

<html>
<head>
<title>Indexed Arrays</title>
</head>

<body>
<h1>Indexed Arrays</h1>
<?php
 $Beatles = array();
 $Beatles[0] = 'John';
 $Beatles[1] = 'Paul';
 $Beatles[2] = 'George';
 $Beatles[3] = 'Ringo';

 echo $Beatles[2]; //outputs George to the browser

 $Beatles[] = 'Nat';
?>
<hr/>
<?php
 foreach ($Beatles as $Beatle)
 {
  echo "$Beatle<br/>";
 }
?>
</body>
</html>

Exercise: Working with Indexed Arrays

Duration: 10 to 15 minutes.

In this exercise, you will use arrays to create a table with a single column that lists all your favorite colors. (see footnote) As shown in the screenshot below, the background of each table row should be the same as the color named in the row.

  1. Open Arrays/Exercises/ColorTable.php for editing.
  2. Create an array that holds your favorite colors.
  3. Inside of the open and close <table> tags, loop through the array outputting a table row for each element.
  4. Test your solution in a browser.

Associative Arrays

Whereas indexed arrays are indexed numerically, associative arrays are indexed using names. For example, instead of Ringo being indexed as 3, he could be indexed as “drummer”.

Initializing Associative Arrays

Like with indexed arrays, we can intialize a zero-length associative array and then add elements.

Syntax
$Beatles = array();
$Beatles['singer1'] = 'Paul';
$Beatles['singer2'] = 'John';
$Beatles['guitarist'] = 'George';
$Beatles['drummer'] = 'Ringo';

Or the array could be created in a single line as follows.

Syntax
$Beatles = array('singer1' => 'John',
                 'singer2' => 'Paul',
                 'guitarist' => 'George',
                 'drummer' => 'Ringo');

Reading from Associative Arrays

Reading from associative arrays is as simple as reading from indexed arrays.

Syntax
echo $Beatles['drummer']; //outputs Ringo to the browser

Looping through Associative Arrays

The following code will loop through the entire $Beatles array outputting each element and its key to the browser.

Syntax
foreach ($Beatles as $key => $Beatle)
{
 echo "<b>$key:</b> $Beatle<br>";
}

The above code snippets are combined in the following example.

Code Sample: Arrays/Demos/AssociativeArrays.php

<html>
<head>
<title>Associative Arrays</title>
</head>

<body>
<h1>Associative Arrays</h1>
<?php
 $Beatles = array('singer1' => 'John',
     'singer2' => 'Paul',
     'guitarist' => 'George',
     'drummer' => 'Ringo');

 echo $Beatles['drummer']; //outputs Ringo to the browser
?>
<hr/>
<?php
 foreach ($Beatles as $key => $Beatle)
 {
  echo "<b>$key:</b> $Beatle<br/>";
 }
?>
</body>
</html>

Superglobal Arrays

The superglobal arrays are associative arrays. The file below outputs all the contents of the superglobal arrays using foreach loops.

Code Sample: Arrays/Demos/SuperGlobals.php

<?php
 session_start();
?>
<html>
<head>
<title>Superglobal Arrays</title>
</head>

<body>
<h1>Superglobal Arrays</h1>
<h2>$_COOKIE</h2>
<ol>
<?php
 foreach ($_COOKIE as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_ENV</h2>
<ol>
<?php
 foreach ($_ENV as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_FILES</h2>
<ol>
<?php
 foreach ($_FILES as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_GET</h2>
<ol>
<?php
 foreach ($_GET as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_POST</h2>
<ol>
<?php
 foreach ($_POST as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_REQUEST</h2>
<ol>
<?php
 foreach ($_REQUEST as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_SESSION</h2>
<ol>
<?php
 foreach ($_SESSION as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
<hr/>
<h2>$_SERVER</h2>
<ol>
<?php
 foreach ($_SERVER as $key => $item)
 {
  echo "<li><b>$key:</b> $item<br/></li>";
 }
?>
</ol>
</body>
</html>

Don’t worry about the session_start() statement at the top. We’ll cover that in detail later in the course.

Exercise: Working with Associative Arrays

Duration: 10 to 15 minutes.

In this exercise, you will use arrays to create a table with two columns that lists all your favorite colors and their hexadecimal equivalents. The background of each table row should be the same as the color named in the row as shown in the screenshot below.

  1. Open Arrays/Exercises/ColorTable2.php for editing.
  2. Create an associative array that holds color hex codes indexed by their color names, which can be found at http://www.w3schools.com/html/html_colornames.asp.
  3. After the existing table row, write code to loop through the array outputting a table row with two columns for each element in the array.
  4. Test your solution in a browser.

Two-dimensional Arrays

In PHP, two-dimensional arrays are arrays that contain arrays. You can think of the outer array as containing the rows and the inner arrays as containing the data cells in those rows. For example, a two-dimensional array called $Rockbands could contain the names of the bands and some of the songs that they sing. Below is a grid that represents such a two-dimensional array.

Rockband Song1 Song2 Song3
Beatles Love Me Do Hey Jude Helter Skelter
Rolling Stones Waiting on a Friend Angie Yesterday’s Papers
Eagles Life in the Fast Lane Hotel California Best of My Love

The following code creates this two-dimensional array. The internal arrays are highlighted. Note that the header row is not included.

Syntax
$Rockbands = array(
 array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'),
 array('Rolling Stones','Waiting on a Friend','Angie',
   'Yesterday\'s Papers'),
 array('Eagles','Life in the Fast Lane','Hotel California',
   'Best of My Love')
)

Reading from Two-dimensional Arrays

To read an element from a two-dimensional array, you must first identify the index of the “row” and then identify the index of the “column.” For example, the song “Angie” is in row 1, column 2, (see footnote) so it is identified as $Rockbands[1][2].

Looping through Two-dimensional Arrays

To loop through a two-dimensional array, you need to nest one loop inside of another. The following code will create an HTML table from our two-dimensional array.

Syntax
<table border="1">
<?php
foreach($Rockbands as $Rockband)
{
 echo "<tr>";
 foreach($Rockband as $item)
 {
  echo "<td>$item</td>";
 }
 echo "</tr>";
}
?>
</table>

The above code snippets are combined in the following example to output a Rockbands table.

Code Sample: Arrays/Demos/TwoDimensionalArrays.php

<html>
<head>
<title>Two-dimensional Arrays</title>
</head>

<body>
<h1>Two-Dimensional Arrays</h1>
<?php
$Rockbands = array(
 array('Beatles','Love Me Do', 'Hey Jude','Helter Skelter'),
 array('Rolling Stones','Waiting on a Friend','Angie','Yesterday\'s Papers'),
 array('Eagles','Life in the Fast Lane','Hotel California','Best of My Love')
);
?>
<table border="1">
<tr>
 <th>Rockband</th>
 <th>Song 1</th>
 <th>Song 2</th>
 <th>Song 3</th>
</tr>
<?php
foreach($Rockbands as $Rockband)
{
 echo '<tr>';
 foreach($Rockband as $item)
 {
  echo "<td>$item</td>";
 }
 echo '</tr>';
}
?>
</table>
</body>
</html>

Array Manipulation Functions

The following table shows some of the more common array manipulation functions.

Useful Array Functions (see footnote)
Function Explanation
sort() Sorts an array alphabetically. Elements will be assigned to new index numbers.
asort() Sorts associative arrays alphabetically by value. The index association remains intact.
ksort() Sorts associative arrays alphabetically by key. The index association remains intact.
rsort() Reverse sorts an array alphabetically. Elements will be assigned to new index numbers.
arsort() Reverse sorts associative arrays alphabetically by value. The index association remains intact.
krsort() Reverse sorts associative arrays alphabetically by key. The index association remains intact.
shuffle() Randomly sorts the array. For the order to be sorted differently each time, the random number generator needs to be seeded with rsand().
array_reverse() Returns an array with the elements in reverse order.
array_walk() Applies a user function to every element of an array.
count() Returns the number of elements in an array.
explode() Converts a string to an array by splitting it on a specified separator.
is_array() Takes one parameter and returns true or false depending on whether the parameter passed is an array.
array_keys() Returns all the keys of an associative array as an array.
array_key_exists() Checks to see if a specified key exists in an array.

Arrays Conclusion

Arrays are an important feature of many modern programming languages. In this lesson, we have covered the most common uses of arrays.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s