In programming, arrays are an important concept. An array is a list of things. The list can be pretty much anything, including strings. We’ll take a look at a fairly basic array.
Code Dissection
Here we have a fruity array with three fruits in it.
$fruits = ["apple", "pear", "orange"];
[
The left opening bracket starts the list of things.
“apple”,
Each thing in this array is a string. The commas separate the things in the array. The comma after the last string (“orange”) is optional. The spaces after each comma are optional, but they help readability.
];
The right bracket closes the array, and the semicolon ends the statement.
$firstFruit = $fruits[0];
The array of items wouldn’t be very useful if we couldn’t access the items.
$fruits
This is our array of three strings.
[
If a variable holds an array, use a left bracket ([), an index (0), and right bracket (]) to access an item in the array.
0
The number in between the brackets is called an index. The index is the position of the item we want to grab. The first item is in position 0. The next item is in position 1. The third item would be at index 2.
];
Close the statement with a right bracket and semicolon.
The $firstFruit variable, now, has a string (”apple”) assigned to it, but the array remains unchanged.
PHP has a special array called on associative array that lets us specify the index, but, in this case, the index is called a key.
$user = [ "name'' => "John", "email" => "john@email.com'' ];
“name”
The key of the first item is “name”.
=>
The equals and greater than sign combo is used to connect the key to the value.
$userEmail = $user['email'];
[
We use a left angle bracket to access something in the $user array.
’email’
But this time, we use a named key (a string) to get the item (john@email. com) instead of using an index.
The $userEmail variable now has the string “john@email.com” assigned to it.
An associative array is not better than a normal indexed array. It just provides different functionality. For example, a very common pattern is to create an array of associative arrays.
$users = [
['name' => 'John', 'email' => 'jon@email.com'],
['name' => 'Mary', 'email' => 'mary@email.com'],
];
Just like a normal array, the array of associative arrays starts with an opening bracket. The new line after the opening bracket helps readability, but it’s not required. PHP ignores new lines for the most part.
[ “name” => “John”, “email” => “john@email.com” ]
The first item in our array is an entire associative array. Putting each associative array on its own line helps with readability.
,
Just like with a normal array, use a comma to separate each item.
$firstUser = $users[0];
We get the first user just like we got the first fruit, using an index.