Science Library - free educational site

Arrays (PHP)

An array is a variable which contains more than one piece of information. For example, the momo40k.ch club has more than one member. We can create an array called $members, and put a series of key-value pairs into it.

<?php

$members = array('Sean', 'Daniele', 'Cesare', 'Andrew');

echo $members[0];

?>

The name 'Sean' will be printed, since arrays are indexed starting from 0. $members[2] contains the value of the third element, 'Cesare'.

Array can be indexed by a series of key-value pairs. For example, the days of the week can be given numeric keys 1 to 7 like this:

<?php

$workdays = array(1 => 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday');

echo $workdays[3].'
';

?>

This will print 'Wednesday', since the key '3' will have been assigned the value 'Wednesday' in the above declaration. An array that uses numbers as keys is known as an indexed array.

Strings may also be used as keys. This is known as an associative array.

<?php

$positions = array('Accountant' => 'Freddie McGurty', 'Cashier' => 'Frieda Frederickson', 'Clerk' => 'Goodwill Friday');

echo $positions['Cashier'];

?>

This code will return and print 'Frieda Frederickson', since that is the value contained in the key 'Cashier', inside the array $positions.

<?php

$positions = array('Accountant' => 'Fred McGurty', 'Cashier' => 'Frieda Frederickson', 'Clerk' => 'Goodwill Friday');

echo 'This is the cashier in our company: {$positions['Cashier']};

?>

When printing out an array element inside a string, it is necessary to specify that it is an array element using the curly brackets {}. Without these, the programme interprets the quotes around the key literally and returns a parse error.

Superglobal Arrays

These are predefined:

  • $_GET: stores the values sent to a PHP script via the get method, which places the data in the URL.
  • $_POST: an alternative method of storing data from an HTML form.
  • $_SERVER: calls information about the server.
  • $ENV: calls information about the server.
  • $_SESSION: an array created for a session.
  • $_COOKIE: an array used for logging information on the user's computer during a session.
Range

A useful function for creating arrays, such as for drop-down lists, is the range() function.

To store the numbers one to hundred in an array sequentially, assign an array the values via the range function: $count = range(1, 100);

To store the letters of the English alphabet in an array sequentially, assign an array the values via the range function: $letters = range(a, z);

To determine how many elements an array contains: $num = count($array);

Use the is_array() function to check that a variable is an array type.

foreach

To access every element in an array:

<?php

foreach ($array as $value) {

//perform some action on $value

}

?>

For example, to print all the numbers 1 to 10:

<?php

$ten = range(1, 10);

foreach ($ten as $number) {

echo $number.'
';

}

?>

The keys can also be iterated in a similar manner:

<?php

$fibonacci = array(1 => 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 );

foreach ($fibonacci as $key => $value) {

echo 'The number '.$key.' element in the Finonacci sequence is '.$value.'
';

}

?>

An example for a dropdown menu for the months of the year:

<?php

$date = range(1, 31);

$months = array(1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

echo '<select name='month'>';

foreach ($months as $k => $v) {

echo "<option value=\"$k\">$v</option>\n";

}

echo '</select>';

?>

Sorting Arrays

$scientists = array(1 => 'Einstein', 2 => 'Newton', 3 => 'Galileo', 4 => 'Bohr');

Sort by value (loss of key)

sort($scientists); returns an alphabetically ordered list of elements.

This sort discards the original keys, and rearranges the array by values (by number or alphabet, ascending).

A printout of key - value would return:

1 - Bohr, 2 - Einstein, 3 - Galileo, 4 - Newton

Sort by value (retaining key)

asort($scientists); returns an alphabetically ordered list of elements, but key retained.

A printout of key - value would return:

4 - Bohr, 1 - Einstein, 3 - Galileo, 2 - Newton

Sort by key

ksort($scientists); returns an key ordered list of elements, but key retained.

A printout of key - value pairs would return:

1 - Einstein, 2 - Newton, 3 - Galileo, 4 - Bohr

Sort in reverse

rsort($scientists); returns a key ordered list of elements, but key retained.

This sort discards the original keys, and rearranges the array by values (by number or alphabet, descending).

A printout of key - value would return:

1 - Newton, 2 - Galileo, 3 - Einstein, 4 - Bohr

arsort and krsort are also possible.

Shuffle

shuffle() randomises the order of elements in an array.

Multidimensional arrays

Multidimensional arrays contain more information than a standard array.

An array of constants is like a street full of single-storey buildings. Each street number represents, sequentially, a single house.

A multidimensional array is like a street full of multi-storey buildings. Each street number takes you to a different building, and each of these buildings contains an index of many flats.

To create a multidimensional array, we create a series of single arrays (e.g. an array for each customer, containing first name, last name, address, telephone number), and because we have several (or several hundred, there is no limit) of these with the same keys (first name, last name, address, telephone number), we can put them into one multi-d array.

<?php

$cust1 = array(fname => 'Fred', lname => 'McGurty', address => '42 Bardvast St., Magrathea', tel => '04242424242',);

$cust2 = array(fname => 'Zaphod', lname => 'Beeblebrox', address => 'Vortex Deadend, Somewhere Out There', tel => '0420420420',);

$customers = array('Cust1' => $cust1, 'Cust2' => $cust2);

echo $customers['Cust1']['address'];

?>

The above example is of an associative array, in which keys are strings (fname, lname, address, tel). Keys can also be numbers. If keys are not nominated, elements are arranged automatically as numbers, starting at 0.

<?php

$dogs = array('dachshund', 'terrier', 'alsatian');

$birds = array('kookaburra', 'ostrich', 'eagle', 'thrush');

$creatures = array($dogs, $birds);

echo $creatures[1][0];

?>

The above script prints out the first ([0]) element of the second ([1]) array in the multidimensional array called $creatures: 'kookaburra'. Notice that the individual arrays do not have to be of the same length. Calling $creatures[0][3], for example, would return an empty string, since there is no 4th element of the $dogs sub-array.

These examples demonstrate the convenience of storing a large amount of data in a multidimensional array. But they are also very powerful when used in conjunction with a foreach() function, for loading or retrieving large amounts of data, particularly from a database.

<?php

$dogs = array('dachshund', 'terrier', 'alsatian');

$birds = array('kookaburra', 'ostrich', 'eagle', 'thrush');

$fish = array('trout', 'salmon', 'cod', 'Loch Ness Monster');

$creatures = array('Dogs' => $dogs, 'Birds' => $birds, 'Fish' => $fish);

foreach ($creatures as $type => $name) {

echo "<h3>$type</h3><ul>";

foreach ($name as $v) {

echo "<li>$v</li>\n";

}

echo '</ul>';}

?>

In the above example, two foreach() loops are used. The first one, foreach ($creatures as $type => $name), cycles through all the sub-arrays in the $creatures multi-d array, assigning the keys each time to a new variable $type. This is printed out at the start of each loop as the title in <h3>$type</h3>. The value of $type is an array, so these are looped through in a second foreach loop, and printed out as a list <li>$v</li>\n.

Note the use of \n within a string denotes a line return. The HTML character <br /> could be used as well.

Receiving list data from an HTML form

HTML forms with a series of checkboxes can send the user's selections to a PHP script in the form of a multi-dimensional array.

<input type="checkbox" name="dog[]" value="dachshund" />Dachshund

<input type="checkbox" name="dog[]" value="terrier" />Terrier

<input type="checkbox" name="dog[]" value="alsatian" />Alsatian

echo '</ul>';}

In the above example, an HTML form asks the user to select one of the three options. If the form's method is 'POST', then when the form is submitted it will send a multi-dimensional array called $_POST[]. One element of this multi-d array is the array $_POST['dog'], with possible values $_POST['dog'][0], $_POST['dog'][1], and $_POST['dog'][2], depending on which checkbox was selected.

The select menu may also allow for multiple selections:

<select name="dog[]" multiple="multiple" />

<option value="dachshund" />Dachshund </option>

<option value="terrier" />Terrier </option>

<option value="alsatian" />Alsatian </option>

</select>

Content © Andrew Bone. All rights reserved. Created : June 3, 2014 Last updated :February 14, 2016

Latest Item on Science Library:

The most recent article is:

Air Resistance and Terminal Velocity

View this item in the topic:

Mechanics

and many more articles in the subject:

Subject of the Week

Mathematics

Mathematics is the most important tool of science. The quest to understand the world and the universe using mathematics is as old as civilisation, and has led to the science and technology of today. Learn about the techniques and history of mathematics on ScienceLibrary.info.

Mathematics

Great Scientists

Johann(II) Bernoulli

1710 - 1790

Johann Bernoulli (II) was the son of Johan (I), and the younger brother of Daniel and Nicolaus, all noted mathematicians.

Johann Bernoulli (II), 1710 - 1790
IT Forum by Sean Bone

Quote of the day...

Like wine through water, it has altered the colour of my mind.

ZumGuy Internet Promotions

SaraOrdine