📖 PHP Arrays

Arrays in PHP are a way to store multiple pieces of data under a single variable name. Each piece of data is called an element, and each element can be accessed by its index or key. There are three main types of arrays in PHP:

Indexed (Numeric) Arrays
Arrays where elements are indexed numerically, starting at 0.
Associative Arrays
Arrays where elements are indexed by keys, which can be strings.
Multidimensional Arrays
Arrays that contain other arrays as elements, allowing multiple levels of data storage.

Numeric (Indexed) Arrays

  • Elements are numbered, starting from 0 by default.
  • You can refer to an element by its index number, using square brackets: $myArray[3]
  • Arrays can be created and populated at the same time:
<?php
$daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
?>

Notice that elements are automatically indexed from 0 when not explicitly defined. You can also assign custom indexes:

<?php
$daysOfWeek = [1 => "Sunday", 2 => "Monday", 3 => "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
?>

If you define the first index manually, subsequent elements follow sequentially.

  • You can create an array by directly assigning values to specific indexes: $daysOfWeek[1] = "Sunday";
  • You can add to an array by directly assigning values to specific indexes: $petSounds["snake"] = "hiss";
  • To add elements to the end of an array without specifying an index: $daysOfWeek[] = "Monday";

Associative Arrays

  • In associative arrays, elements are assigned a string key (index) instead of a numeric index.
  • These arrays are very common in PHP due to their flexibility in storing data.
<?php
	$petSounds = ["dog" => "bark", "cat" => "purr", "bird" => "tweet"];
?>
  • To access an element in an associative array, use the string key: $petSounds["dog"] returns "bark".
  • To add an additional array element to an associative array, use $array["key"] = "value";. IE: $petSounds["snake"] = "hiss";
print_r()

The print_r() function can be used to display the structure and contents of the array for debugging purposes.

<?php
	print_r($petSounds);
?>

The print_r($petSounds) returns the following:

Array ( [dog] => bark [cat] => purr [bird] => tweet )

This is easy enough to read for a simple array, but when they become more complex, as they do in multi-dimensional arrays, it can be difficult to read. You can improve the readability of the print_r() function by adding <pre> tags and assign the array value to a variable for display anywhere in the script or on the page.

<?php
	$petSounds = ["dog" => "bark", "cat" => "purr", "bird" => "tweet"];
	?>
	$arrayContents = print_r($petSounds, true);

    echo "<pre>$arrayContents</pre>";

Notice that to use the print_r() values in a variable, you must supply a second arguement with the value true. This will maintain a cleaner and more readable output.

Array
(
	[dog] => bark
	[cat] => purr
	[bird] => tweet
)

Loops: Iterating Over Arrays

The foreach loop is designed to iterate over arrays, executing code for each element.

Using foreach with Indexed Arrays
<?php
	$animals = ["dog", "cat", "bird"];
	foreach ($animals as $animal) {
		echo "$animal<br>";
	}
?>

The above loop prints each animal name on a new line:

dog
cat
bird

Using foreach with Associative Arrays

With associative arrays, you can iterate through both the keys and the values:

<?php
	$petSounds = ["dog" => "bark", "cat" => "purr", "bird" => "tweet"];
	foreach ($petSounds as $animal => $sound) {
		echo "A $animal will $sound.<br>";
	}
?>

This would print:

A dog will bark.
A cat will purr.
A bird will tweet.

Common Array Functions

PHP provides many built-in functions to manipulate arrays. Here are some commonly used ones:

count($array)
Returns the number of elements in the array.
array_push($array, $value)
Adds one or more elements to the end of a numeric array.
array_merge($array1, $array2)
Merges two or more arrays together.

Using Arrays in HTML

To insert array content into an HTML page, the values can be dynamically added to variables and then displayed within the HTML structure:

<?php
	$petSounds = ["dog" => "bark", "cat" => "purr"];
	$petSounds["bird"] = "tweet"; // add a new array element separately
	$pageContent = "";

	foreach ($petSounds as $animal => $sound) {
		$pageContent .= "<p>A $animal will $sound.</p>\n";
		// the \n will create line breaks in the source code for improved readability
	}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pet Sounds</title>
</head>
<body>
    <?= $pageContent; ?>
</body>
</html>

The HTML output will look like this:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pet Sounds</title>
</head>
<body>
    <p>A dog will bark.</p>
    <p>A cat will purr.</p>
    <p>A bird will tweet.</p>
</body>
</html>