PHP Lessons - Lesson 10 - Arrays
Up to this lesson, we’ve only been working with numeric and string variables. Now, let’s explore arrays in PHP. Arrays can contain both numeric and string variables, which is why they are called arrays.
The concept is simple: arrays consist of multiple keys and corresponding values. For example, keys can be 1, 2, 3, and the values could be 4, 'Hello World', or true. Arrays in PHP are declared like regular variables, with the dollar sign:
$tree = array();
To create an array, we use the array()
function.
Note: Declaring variables or arrays explicitly in PHP isn’t required. However, it’s good practice for understanding code structure and variable types.
Here’s how we define a sample array:
<?php $tree = array( 1 => 4, 2 => 'Hello World', 3 => true, ); ?>
Pay attention to the syntax: the variable is assigned using = array()
, followed by pairs of key => value
.
array( key1 => value1, key2 => value2, );
Each key-value pair is separated by a comma. Arrays can also be written in a single line:
<?php $tree = array(1 => 4, 2 => 'Hello World', 3 => true); ?>
Both formats are valid. The multi-line version is easier to read.
To print an array, use print_r()
(not print
):
<?php $tree = array( 1 => 4, 2 => 'Hello World', 3 => true, ); print_r($tree); ?>
Output: Array ( [1] => 4 [2] => Hello World [3] => 1 )
To make the output more readable, wrap it with a <pre>
tag:
<?php $tree = array( 1 => 4, 2 => 'Hello World', 3 => true, ); print '<pre>'; print_r($tree); print '</pre>'; ?>
You’ll see a nicely formatted structure:
Array ( 1 => 4, 2 => 'Hello World', 3 => true, )
To access a specific element of the array:
<?php print $tree[2]; // Outputs: Hello World ?>
To add an element to an array:
$tree[] = 'Another item';
Or with a specific key:
$tree[6] = 'New item';
Overwriting an existing key:
$tree[3] = 'Replaced item';
You can also use string keys:
$tree['key3'] = true; print $tree['key3'];
PHP Multidimensional Arrays
Multidimensional arrays hold arrays within arrays. A good example is a multiplication table:
<?php $multi = array(); $multi[1][1] = 1; $multi[1][2] = 2; $multi[1][3] = 3; $multi[2][1] = 2; $multi[2][2] = 4; $multi[2][3] = 6; $multi[3][1] = 3; $multi[3][2] = 6; $multi[3][3] = 9; print '<pre>'; print_r($multi); print '</pre>'; ?>
Each element is accessed with two keys, like $multi[2][3]
. Arrays can also be defined in one statement:
$multi = array( 1 => array(1 => 1, 2 => 2, 3 => 3), 2 => array(1 => 2, 2 => 4, 3 => 6), 3 => array(1 => 3, 2 => 6, 3 => 9), );
If I come across more useful array examples later, I’ll add them in upcoming lessons. Let’s continue!