PHP Simple Arrays

What is a Simple Array

Simple arrays are arrays that are indexed using numbers and is the default behavior for arrays in PHP.

Declaring an Array

There are two way to declare an array in PHP, with the array function OR using the array literal.

$names = array();
$names = [];

Both methods create an empty array so that you can place items inside of it. If you want, you can create a simple array that contains items by added a comma-separated list, using either the array function or the array literal.

$names = array("Oscar", "Brent", "Davis", "Hank");
$names = ["Oscar", "Brent", "Davis", "Hank"];

Both examples will create an array with the four initial names but can still have more added afterwards.

Retrieving Array Values

The items inside the array are numbered from zero to three. We could write these items out like this:

echo $names[0]; // Oscar
echo $names[3]; // Hank

Retrieving Array Length

If you want to find out how many items are inside an array, you can use either the sizeof() OR count() function. NOTE: Both functions are exactly the same, as sizeof() is simply an alias of count().

echo sizeof( $names ); //outputs 4
echo count( $names ); //outputs 4

Updating Array Values

If you want to update an item in an existing array, use the same syntax to retrieve followed by the assignment operator and the new value.

$names[1] = "Fitzy"; // $names = ["Oscar", "Fitzy", "Davis", "Hank"]
$names[3] = "Bob"; // $names = ["Oscar", "Fitzy", "Davis", "Bob"]

This will replace the name "Brent" with the name "Fitzy" and the name "Hank" with the name "Bob"

Adding a New Item to an Array

If you want to add a new item to an existing simple array then we use a similar syntax to the update. We add the square brackets after the array name but we leave them empty.

$names[] = "Bill"; // $names = ["Oscar", "Fitzy", "Davis", "Bob", "Bill"]

This will add the name "Bill" to the end of the array.