Arrays

1

Simply put, an array is a set of values. Before this lesson we dealt with variables when one variable held one value. Arrays let you hold many values in a single variable. Here is an example of a simple PHP array:

$numbers = [1, 8, 10, 4, 2];

You can access array elements by their index, which is a zero-based position of the element in the array:

$numbers = [1, 8, 10, 4, 2];

echo $numbers[0]; # Prints 1
echo $numbers[1]; # Prints 8
echo $numbers[2]; # Prints 10
echo $numbers[3]; # Prints 4
echo $numbers[4]; # Prints 2

You can use count function to get the number of elements in the array:

$numbers = [1, 8, 10, 4, 2];

echo count($numbers); # Prints 5

An array can be empty. You can check if the array is empty with empty function:

$numbers = [1, 2, 3];
$names = [];

if(empty($numbers)) # Not empty, "if" block will be skipped
{
    echo 'There are no numbers';
}

if(empty($names)) # Empty, "if" block will be executed
{
    echo 'There are no names';
}

Examples above are arrays of values. There are also associative arrays. These are arrays of key-value pairs. Let's look at the example:

$days_in_month =
[
    'january'   => 31,
    'february'  => 28,
    'march'     => 31,
    'april'     => 30,
    'may'       => 31,
    'june'      => 30,
    'july'      => 31,
    'august'    => 31,
    'septembed' => 30,
    'october'   => 31,
    'november'  => 30,
    'december'  => 31
];

$month = 'april';

echo 'There are ' . $days_in_month[$month] . ' days in ' . $month;

# Prints "There are 30 days in april"

In the example above a name of a month is a key and a days count is a value. You can get a value by its key.

You can set array values in the same manner:

$numbers = [1, 8, 10, 4, 2];

$days_in_month =
[
    'january'  => 31,
    'february' => 28
];

$numbers[3] = 50;
echo $numbers[3]; # Prints 50

$days_in_month['march'] = 31;
echo $days_in_month['march']; # Prints 31

You can check if there is a value in the associative array at a given key with isset function:

$days_in_month =
[
    'january'  => 31,
    'february' => 28
];

if(isset($days_in_month['march']))
{
    echo $days_in_month['march'];
}
else
{
    echo 'Month not found'; # There is no "march" key so it will print that
}

You can remove a key-value pair from the associative array by the key with unset function:

$days_in_month =
[
    'january'  => 31,
    'february' => 28
];

unset($days_in_month['january']);

var_dump($days_in_month); # Prints the array with the only one key-value pair
Lesson 3
Share this page:

Learning plan

Choose the best way to start, and let's start!
Embedding PHP script into HTML
The very basics of PHP variables
4. Arrays
The very basics of PHP arrays
The things you should know about PHP type system
The basement of PHP control flow structures you should learn before continue
It's time to create your own PHP functions