Core PHP 7 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Explain why arrays are needed and create them with array() and [ ].
  • Work with numeric, associative and multidimensional arrays.
  • Display arrays with print_r() and var_dump(), and loop through them.
  • Use extract(), count(), sorting functions and array destructuring.
Why Arrays?

An array stores multiple values in one single variable. A normal variable is a storage area that holds a number or text – but only one value. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

$cars1 = "Ford";
$cars2 = "Maruti";
$cars3 = "BMW";

But what if you want to loop through the cars and find a specific one? And what if you had not 3 cars but 3000? The best solution is an array. An array holds all the values under a single name, and each element has its own index (key) so that it can be accessed easily.

In PHP there are three kinds of arrays:

  • Numeric (indexed) array – an array with a numeric index.
  • Associative array – an array where each key is associated with a value.
  • Multidimensional array – an array containing one or more arrays.
Numeric Arrays

A numeric array stores each element with a numeric index. There are two ways to create one.

  1. The index is assigned automatically (it starts at 0):
$cars = array("Saab", "Volvo", "BMW", "Toyota");
$cars = ["Saab", "Volvo", "BMW", "Toyota"];   // short syntax (PHP 5.4+)
  1. The index is assigned manually:
$cars[0] = "Saab";
$cars[1] = "Volvo";
$cars[2] = "BMW";
$cars[3] = "Toyota";

In the following example you access the values by referring to the array name and index:

File: htdocs/phpbook/ch09/numeric.php
<?php
$cars[0] = "Saab";
$cars[1] = "Volvo";
$cars[2] = "BMW";
$cars[3] = "Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish cars.<br>";
$cars[] = "Maruti";                 // [] appends at the next index
echo "Number of cars: " . count($cars) . "<br>";
for ($i = 0; $i < count($cars); $i++) {
    echo "$i: $cars[$i]<br>";
}
?>
OUTPUT browser · http://localhost/phpbook/ch09/numeric.php
Saab and Volvo are Swedish cars.
Number of cars: 5
0: Saab
1: Volvo
2: BMW
3: Toyota
4: Maruti
Associative Arrays

In an associative array each key is associated with a value. When storing data about specific named values, a numeric array is not always the best choice. With associative arrays we can use meaningful keys and assign values to them. In this example we use an array to assign ages to different persons:

$ages = array("Peter" => 32, "Quagmire" => 30, "Joe" => 34);

This example creates the same array in a different way:

$ages['Peter'] = 32;
$ages['Quagmire'] = 30;
$ages['Joe'] = 34;

The keys can be used in a script:

File: htdocs/phpbook/ch09/assoc.php
<?php
$ages['Peter'] = 32;
$ages['Quagmire'] = 30;
$ages['Joe'] = 34;
echo "Peter is " . $ages['Peter'] . " years old.<br>";
foreach ($ages as $person => $age) {
    echo "$person => $age<br>";
}
?>
OUTPUT browser · http://localhost/phpbook/ch09/assoc.php
Peter is 32 years old.
Peter => 32
Quagmire => 30
Joe => 34
The extract() function

With extract(), every key of an associative array is converted into a variable with the same name, initialised with the element's value.

File: htdocs/phpbook/ch09/extract.php
<?php
$ages = array("Peter" => 32, "Quagmire" => 30, "Joe" => 34);
$n = extract($ages);
echo "$n variables created.<br>";
echo "Peter is " . $Peter . " years old.<br>";
echo "Joe is $Joe years old.";
?>
OUTPUT browser · http://localhost/phpbook/ch09/extract.php
3 variables created.
Peter is 32 years old.
Joe is 34 years old.

Never call extract() on user input such as $_GET or $_POST: a visitor could then overwrite any variable of your script – the same danger as the old register_globals.

Multidimensional Arrays

In a multidimensional array, each element of the main array can itself be an array, and each element of the sub-array can be an array, and so on. In this example we create a multidimensional array with automatically assigned keys:

File: htdocs/phpbook/ch09/multi.php
<?php
$families = array
(
    "Griffin" => array
    (
        "Peter",
        "Lois",
        "Megan"
    ),
    "Quagmire" => array
    (
        "Glenn"
    ),
    "Brown" => array
    (
        "Cleveland",
        "Loretta",
        "Junior"
    )
);
echo "<pre>";
print_r($families);
echo "</pre>";
echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";
?>
OUTPUT browser · http://localhost/phpbook/ch09/multi.php
Array
(
    [Griffin] => Array
        (
            [0] => Peter
            [1] => Lois
            [2] => Megan
        )

    [Quagmire] => Array
        (
            [0] => Glenn
        )

    [Brown] => Array
        (
            [0] => Cleveland
            [1] => Loretta
            [2] => Junior
        )

)

Is Megan a part of the Griffin family?

print_r() prints an array in a human-readable form; wrapping it in <pre> keeps the indentation in the browser.

A two-dimensional table of marks
File: htdocs/phpbook/ch09/marks.php
<?php
$students = [
    ["roll" => 101, "name" => "Asha",  "php" => 82, "mysql" => 75],
    ["roll" => 102, "name" => "Ravi",  "php" => 64, "mysql" => 70],
    ["roll" => 103, "name" => "Neha",  "php" => 91, "mysql" => 88],
];
echo "<table border='1' cellpadding='5' style='border-collapse:collapse;font-family:Arial;font-size:13px'>";
echo "<tr><th>Roll</th><th>Name</th><th>PHP</th><th>MySQL</th><th>Total</th></tr>";
foreach ($students as $s) {
    $total = $s['php'] + $s['mysql'];
    echo "<tr><td>{$s['roll']}</td><td>{$s['name']}</td><td>{$s['php']}</td>"
       . "<td>{$s['mysql']}</td><td><b>$total</b></td></tr>";
}
echo "</table>";
?>
OUTPUT browser · http://localhost/phpbook/ch09/marks.php
Browser output
Sorting Arrays
FunctionSorts
sort()values in ascending order, re-indexing the keys
rsort()values in descending order
asort()an associative array by value, keeping keys
arsort()by value in descending order, keeping keys
ksort()by key, ascending
krsort()by key, descending
usort()with a user-defined comparison function
File: htdocs/phpbook/ch09/sort.php
<?php
$nums = [40, 10, 30, 20];
sort($nums);
echo "sort: " . implode(", ", $nums) . "<br>";
rsort($nums);
echo "rsort: " . implode(", ", $nums) . "<br>";
$ages = ["Peter" => 32, "Asha" => 21, "Joe" => 34];
asort($ages);
echo "asort: "; print_r($ages); echo "<br>";
ksort($ages);
echo "ksort: "; print_r($ages); echo "<br>";
usort($nums, fn($a, $b) => $a <=> $b);
echo "usort ascending: " . implode(", ", $nums);
?>
OUTPUT browser · http://localhost/phpbook/ch09/sort.php
sort: 10, 20, 30, 40
rsort: 40, 30, 20, 10
asort: Array ( [Asha] => 21 [Peter] => 32 [Joe] => 34 )
ksort: Array ( [Asha] => 21 [Joe] => 34 [Peter] => 32 )
usort ascending: 10, 20, 30, 40
Useful Array Tools
File: htdocs/phpbook/ch09/arraytools.php
<?php
$colors = ["red", "green", "blue"];
echo "in_array('green'): " . (in_array("green", $colors) ? "yes" : "no") . "<br>";
echo "array_search('blue'): " . array_search("blue", $colors) . "<br>";
array_push($colors, "black");          // add at the end
array_unshift($colors, "white");       // add at the beginning
echo "after push/unshift: " . implode(", ", $colors) . "<br>";
$last = array_pop($colors);
echo "array_pop removed: $last<br>";
echo "array_reverse: " . implode(", ", array_reverse($colors)) . "<br>";
[$first, $second] = $colors;           // array destructuring
echo "first = $first, second = $second<br>";
echo "range(1, 5): " . implode(" ", range(1, 5)) . "<br>";
echo "array_sum: " . array_sum([10, 20, 30]);
?>
OUTPUT browser · http://localhost/phpbook/ch09/arraytools.php
in_array('green'): yes
array_search('blue'): 2
after push/unshift: white, red, green, blue, black
array_pop removed: black
array_reverse: blue, green, red, white
first = white, second = red
range(1, 5): 1 2 3 4 5
array_sum: 60

Part II (Chapter 23) lists all array functions.

Key Takeaways
  • An array stores many values under one name; elements are reached by index or key.
  • Numeric arrays start at index 0; $a[] = x appends.
  • Associative arrays use named keys: ["Peter" => 32].
  • Multidimensional arrays contain arrays: $families['Griffin'][2].
  • print_r() / var_dump() display arrays; foreach loops through them.
  • extract() turns keys into variables – never use it on user input.
  • sort, rsort, asort, ksort and usort sort arrays.
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch09 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.

Question / Answer (15 questions)

Answer : A special variable that stores multiple values under a single name; each value (element) is identified by an index or key.

Answer : To handle lists of related values efficiently – for example 3000 car names – so that they can be looped through, searched and sorted, instead of creating thousands of separate variables.

Answer : Numeric (indexed) arrays, associative arrays and multidimensional arrays.

Answer : >
  • The elements of array("Saab", "Volvo") have indexes 0 and 1.
  • <

    Answer : Automatically: $cars = array("Saab", "Volvo", "BMW"); or $cars = ["Saab", "Volvo", "BMW"]; and manually: $cars[0] = "Saab"; $cars[1] = "Volvo"; …

    Answer : An array whose keys are named strings associated with values, e.g. $ages = array("Peter" => 32, "Joe" => 34); then $ages['Peter'] is 32.

    Answer : It imports the elements of an associative array into the current symbol table: each key becomes a variable holding the element's value. It returns the number of variables created.

    Answer : A visitor could add form fields named like your variables and overwrite them – the same security problem that register_globals caused.

    Answer : An array whose elements are themselves arrays, e.g. a list of families where each family is an array of names; elements are accessed with several indexes like $families['Griffin'][2].

    Answer : With print_r($array) (human-readable) or var_dump($array) (with types and lengths), preferably inside <pre> tags in a browser.

    Answer : With count($array) (sizeof() is an alias).

    Answer : sort() sorts the values and re-indexes the array (keys are lost); asort() sorts by value but keeps each key associated with its value, suitable for associative arrays.

    Answer : ksort() for ascending order, krsort() for descending order.

    Answer : To the end with $a[] = $value; or array_push($a, $value); to the beginning with array_unshift($a, $value).

    Answer : Assigning array elements to separate variables in one statement: [$first, $second] = $colors; (or list($first, $second) = $colors;).
    MCQ Test : Check Your Understanding (5 questions)

    Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

    Q1. What is the index of "BMW" in array("Saab", "Volvo", "BMW")?

    Show Answer

    Correct Answer : B. 2
    Numeric arrays start at index 0.

    Q2. $ages = ["Peter" => 32]; creates a(n):

    Show Answer

    Correct Answer : B. Associative array
    The string key "Peter" makes it associative.

    Q3. Which function converts array keys into variables?

    Show Answer

    Correct Answer : C. extract()
    extract() creates variables from array keys.

    Q4. Which function sorts by value and keeps the key–value association?

    Show Answer

    Correct Answer : B. asort()
    asort() keeps keys with their values.

    Q5. $families['Griffin'][2] accesses an element of a:

    Show Answer

    Correct Answer : B. Multidimensional array
    Two indexes are used: the family and the member.

    Bibliography/References

    The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.

    1. The PHP Group. (n.d.). PHP Manual – Arrays. https://www.php.net/manual/en/language.types.array.php
    2. The PHP Group. (n.d.). PHP Manual – Array Functions. https://www.php.net/manual/en/ref.array.php
    3. The PHP Group. (n.d.). PHP Manual – extract. https://www.php.net/manual/en/function.extract.php
    4. The PHP Group. (n.d.). PHP Manual – Sorting Arrays. https://www.php.net/manual/en/array.sorting.php