PHP Arrays: Defining, Looping and Sorting Simple Arrays

Arrays are useful for holding values from database queries or web form entries, where each field (also called a “key”) holds a specific value.

Numbered Arrays

If the programmer does not specify a key for each value in the array, PHP automatically numbers the keys, starting from zero.

This code defines an array $arrMonths[], with each month of the year as an element in the array.


<?php
$arrMonths[] = "January";
$arrMonths[] = "February";
$arrMonths[] = "March";
$arrMonths[] = "April";
?>

The PHP interpreter automatically defines each key in the array with a number, starting from zero:


<?php
$arrMonths[0] = "January";
$arrMonths[1] = "February";
$arrMonths[2] = "March";
$arrMonths[3] = "April";
?>

Array Function

Another method of defining an array is to use the array function:


<?php
$arrMonths= array("January", "February", "March", "April");
?>

This function creates a numbered array in the same way as the enumerated elements in the example above.

Associate Arrays

Associative Arrays are arrays where values are associated to a more descriptive key, and not to a number.

Just as with a numerical array, associative arrays can be be created one element at a time:


<?php
$arrBooks["Comic Books"] = "Superman";
$arrBooks["Science Fiction"] = "Dune";
$arrBooks["Fantasy"] = "The Hobbit";
$arrBooks["Horror"] = "Carrie";
?>

The array function is also useful for creating associative arrays. The "=>" symbol ties the key phrase to the value:


<?php
$arrBooks = array(
"Comic" => "Superman",
"Science Fiction" => "Dune",
"Fantasy" => "The Hobbit",
"Horror" => "Carrie");
?>

is_array Function

Utilize the is_array function to test if a variable is in an array:


<?php
$baseballTeams = array("Cardinals", "Tigers", "Astros");
$footballTeams = "Cardinals, Lions, Texans";

if (is_array($baseballTeams)) {
echo ("Baseball Array
"); } else { echo ("No Baseball Array
"); } if (is_array($footballTeams)) { echo ("Football Array
"); } else { echo ("No Football Array
"); } ?>

In the above code, the $baseballTeams variable is an array (defined by the array function) and the $footballTeams variable is a list of words separated by commas. The code results in:

Baseball Array
No Football Array

Looping Through Arrays

A foreach loop runs through each element in an array; elements in the array can be displayed, have calculations ran on, or perform other operations as they come through the loop.


<?php
$arrBooks = array(
"Comic" => "Superman",
"Science Fiction" => "Dune",
"Fantasy" => "The Hobbit",
"Horror" => "Carrie");

foreach ($arrBooks as $key => $value) {
print  "$value is an example of a $key book.
\n"; } ?>

The results will look like this:

Superman is an example of a Comic book.
Dune is an example of a Science Fiction book.
The Hobbit is an example of a Fantasy book.
Carrie is an example of a Horror book.

Sorting Arrays

The sort function allows for the sorting of an array either numerically (for numerical values) or alphabetically (for string values). The sort function goes through each value and reassigns it a new key:


<?php
$baseballTeams = array("Cardinals", "Tigers", "Astros");
sort($baseballTeams);

foreach ($baseballTeams as $key => $value) {
echo $value. "
\n"; } ?>

The results will read:

Astros
Cardinals
Tigers

PHP Arrays: Defining, Looping and Sorting Simple Arrays

Building a Multidimensional Array

Expanding $arrBooks into a multidimensional array:


<?php
$arrBooks = array(
"Comic" => array(
"Title"=>"Superman",
"Author"=>"Jerry Siegel and Joe Shuster",
"Publication Date" => "1938"),

"Science Fiction" => array(
"Title"=>"Dune",
"Author"=>"Frank Herbert",
"Publication Date"=>"1965"),

"Fantasy" => array(
"Title"=>"The Hobbit",
"Author"=>"J.R.R. Tolkien",
"Publication Date"=>"1937"),   

"Horror" => array(
"Title"=>"Carrie",
"Author"=>"Stephen King",
"Publication Date"=>"1974")
);
?>

Extracting Elements from a Multidimensional Array

To extract a single element from the multidimensional array, you must refer to the keys in both the outer and inner arrays. For instance, the PHP code below:


<?
echo $arrBooks["Science Fiction]["Title"];
echo "<br>";
echo $arrBooks["Horror"]["Author"];
?>

would display:

Dune
Stephen King

Looping Through a Multidimensional Array

The easiest way to loop through a multidimensional array is to nest two foreach loops; the outer loop goes through each outer array element, and the inner loop goes through each inner array element within the selected outer element.


<?
foreach ($arrBooks as $obj_key =>$book)
{
echo "$obj_key Book:<br>";
foreach ($book as $key=>$value){
echo "$key: $value<br>";
}
echo "<br>";
}
?>

The display will look like this:

Comic Book:
Title: Superman
Author: Jerry Siegel and Joe Shuster
Publication Date: 1938

Science Fiction Book:
Title: Dune
Author: Frank Herbert
Publication Date: 1965

Fantasy Book:
Title: The Hobbit
Author: J.R.R. Tolkien
Publication Date: 1937

Horror Book:
Title: Carrie
Author: Stephen King
Publication Date: 1974

Array Functions

Arrays are one of the most useful variable types. Along with its versatility, arrays also can use a variety of functions. In the previous lesson, we used the is_array function to determine if a variable was an array and the sort function to sort the elements of an array. Here are some more examples of array functions.

count($array): Counts the number of elements in an array.

There are 4 books in the collection.

<?
$numBooks = count($arrBooks);
echo "There are $numBooks books in the collection.<br>";
?>

extract($array): Converts associative array keys into string variables. The values of each key become the values of each variable.

Superman is a comic book.
The Hobbit is a fantasy book.

<?
$arrBooks = array(    "Comic" => "Superman",
"ScienceFiction" => "Dune",
"Fantasy" => "The Hobbit",
"Horror" => "Carrie");

extract($arrBooks);
// $arrBooks["Comic"] becomes $Comic
// $arrBooks["ScienceFiction"] becomes $ScienceFiction
// $arrBooks["Fantasy] becomes $Fantasy
// $arrBooks["Horror] becomes $Horror

echo "$Comic is a comic book.<br>";
echo "$Fantasy is a fantasy book.<br>";

?>

extract($array, EXTR_PREFIX_ALL, "prefix"): Adds a prefix to the string variable to differentiate between arrays that have the same keys.

Superman is a comic book.
The Hobbit is a fantasy book.
Superman Returns is a comic film.
Dark Crystal is a fantasy film.

<?
$arrBooks = array(
"Comic" => "Superman",
"ScienceFiction" => "Dune",
"Fantasy" => "The Hobbit",
"Horror" => "Carrie");

extract($arrBooks, EXTR_PREFIX_ALL, "books");
// $arrBooks["Comic"] becomes $books_Comic
// $arrBooks["ScienceFiction"] becomes $books_ScienceFiction
// $arrBooks["Fantasy] becomes $books_Fantasy
// $arrBooks["Horror] becomes $books_Horror

echo "$books_Comic is a comic book.<br>";
echo "$books_Fantasy is a fantasy book.<br>";

$arrFilms = array(
"Comic" => "Superman Returns",
"ScienceFiction" => "Terminator",
"Fantasy" => "Dark Crystal",
"Horror" => "Friday the 13th");

extract($arrFilms, EXTR_PREFIX_ALL, "films");
// $arrFilms ["Comic"] becomes $films_Comic
// $arrFilms ["ScienceFiction"] becomes $films_ScienceFiction
// $arrFilms ["Fantasy] becomes $films_Fantasy
// $arrFilms ["Horror] becomes $films _Horror

echo "$films_Comic is a comic film.<br>";
echo "$films_Fantasy is a fantasy film.<br>";
?>

compact(var1, var2, var3): Converts a list of variables into an array.

Batman is an example of a Comic book.
Dreaming Void is an example of a ScienceFiction book.
American Gods is an example of a Fantasy book.
Frankenstein is an example of a Horror book.

<?
$Comic = "Batman";
$ScienceFiction = "Dreaming Void";
$Fantasy = "American Gods";
$Horror = "Frankenstein";

$arrBooks2 = compact ("Comic", "ScienceFiction", "Fantasy", "Horror");

foreach ($arrBooks2 as $key => $value) {
print  "$value is an example of a $key book.<br>\n";
}
?>

PHP Arrays: Array Functions and Multidimensional Arrays