Last updated on November 28th, 2023
What is an array in PHP?
An array in PHP is a data structure that allows you to store multiple values in a single variable. These values can be of different types, such as integers, strings, or even other arrays (array of arrays).
Each array value is automatically assigned an ID number, called an “index” or a “key”, with the default starting number being 0. (The index/key can be either numeric or a string, depending on the type of array.)
When calling an array value, it must be referred to by its ID number enclosed in square brackets, for example:
<?php $variable = array("value1", "value2", "value3"); echo $variable[0]; ?>
The result of the above code will be to display the value1, since it is the value with ID 0 (by default).
Why are arrays important in PHP?
Arrays are a fundamental data structure in PHP and programming in general for several reasons:
– Organization: They allow you to organize and manage related data efficiently.
– Flexibility: Arrays can store data of different types and can grow or shrink dynamically, making them versatile for various tasks.
– Access: You can quickly access elements in an array by their index or key, which is crucial for data retrieval and manipulation.
– Iteration: Arrays make it easy to iterate over a collection of data, performing operations on each element.
– Data Structures: Arrays are used as the foundation for more complex data structures, such as lists, stacks, and queues.
What types of arrays are there?
PHP supports several types of arrays, with the most common ones being:
1. Indexed Arrays
These are arrays where the keys are numeric, and they start from 0. Indexed arrays are used when you have a list of items, and you want to access them by their position.
Example:
<?php $fruits = array("apple", "banana", "cherry"); echo $fruits[0]; ?>
The above code will display the word “apple” because by default this value is numbered zero (the default key of the value “apple” is 0). Remember that the key must be enclosed in square brackets.
Note: The identification number of the values in the array can also be explicitly specified. In such a case, the starting number does not necessarily have to be 0. You can use any number as you see fit, for example:
<?php $fruits[5] = "apple"; $fruits[9] = "banana"; $fruits[14] = "cherry"; echo $fruits[9]; //Will display "banana" ?>
You can set only the first number and the rest will be assigned automatically, for example:
<?php $food = array(10 => "apples", "tomatoes", "chicken"); echo $food[12]; //Will display "chicken" ?>
Since the first value is assigned key 10, the remaining two values are automatically assigned keys 11 and 12.
In addition to numbers, you can also use words as keys, for example:
<?php $food["vegetables"] = "tomatoes"; $food["fruits"] = "apples"; $food["meat"] = "chicken"; echo $food["fruits"]; //Will display "apples" ?>
2. Associative Arrays
In associative arrays, keys are strings that you assign to each value. These arrays are used when you want to create a mapping between keys and values.
Example:
<?php $person = array("first_name" => "John", "last_name" => "Doe", "age" => 30); echo $person["first_name"]; ?>
This code will display the first name i.e. John. In this case the array syntax is
<?php $variable = array(key1 => value1, key2 => value2, key3 => value3); echo $variable[key1]; ?>
i.e. each key points with the equals and arrow (=>) symbols to its value, with key-value pairs separated by commas.
3. Multidimensional Arrays
These are arrays of arrays. You can create arrays within arrays to represent more complex data structures, like tables or matrices.
Example:
<?php $matrix = array( array("one", "two", "three"), array("four", "five", "six"), array("seven", "eight", "nine") ); echo $matrix[1][2]; //Will display "six" ?>
In the above example we have a matrix of 3 rows and 3 columns. The default row and column keys are 0, 1 and 2, i.e. the first row is automatically assigned ID 0, the second 1, and the third 2. The same is true for the columns – they are automatically assigned IDs 0, 1, and 2. So, via $matrix[1][2] we call the value from the second row (“four”, “five”, “six”) and the third column, which is six.
What are the basic array operations?
1. Accessing Elements
You can access array elements using their index or key. For example:
<?php $fruits = array("apple", "banana", "cherry"); echo $fruits[1]; // Outputs "banana" ?>
2. Adding Elements
You can add elements to an array using the [] notation or the array_push() function. For example:
<?php $fruits = array("apple", "banana", "cherry"); $fruits[] = "grape"; // Adds "grape" to the end of the array echo $fruits[3]; //Display "grape" ?>
3. Modifying Elements
You can change the value of an element by referring to its index or key. For example:
<?php $fruits = array("apple", "banana", "cherry", "grape"); $fruits[0] = "orange"; // Changes the first element to "orange" echo $fruits[0]; //Display "orange" ?>
4. Counting Elements
You can find the number of elements in an array using the count() function. For example:
<?php $fruits = array("orange", "banana", "cherry", "grape"); $count = count($fruits); // $count will be 4 echo $count; // Will display 4 ?>
5. Iterating through Arrays
You can use loops like foreach to iterate through all elements of an array. For example:
<?php $fruits = array("orange", "banana", "cherry", "grape"); foreach ($fruits as $fruit) { echo $fruit . ", "; } // Outputs: "orange, banana, cherry, grape" ?>
The foreach() function loops through the entire array and assigns the list of array elements to a variable.
The syntax of the foreach() function is:
foreach($array_name as $variable_name) {executable code with the variable}
I.e. the name of the array, the keyword as and after it – the name of a variable to which the entire array is assigned as a value is written in the round brackets. Then, inside the big brackets, an action is set with the variable that received the array’s content as its value.
Examples of using arrays in PHP
Indexed Array:
<?php // Create an indexed array of colors $colors = array("Red", "Green", "Blue"); // Access and display the second element (Green) echo "Second color: " . $colors[1]; ?>
In this example, we create an indexed array named $colors that contains three color names. We then access and display the second color, which is “Green” and its key is 1 (the first key is 0 by default).
Associative Array:
<?php // Create an associative array of a person's details $person = array( "name" => "Alice", "age" => 30, "city" => "New York" ); // Access and display the person's age echo "Age: " . $person["age"]; ?>
Here, we use an associative array named $person to store details about a person. We access and display the person’s age, which is 30, by using the “age” key.
Adding and modifying array elements:
<?php // Create an indexed array of fruits $fruits = array("Apple", "Banana"); // Add a new fruit to the array $fruits[] = "Orange"; // Modify the second fruit $fruits[1] = "Grapes"; // Display the updated array echo "Fruits: " . implode(", ", $fruits); ?>
This code starts with an indexed array of fruits, adds “Orange” to the end of the array, and changes the second element to “Grapes.” Finally we use the implode() function to return and show the string from the elements of an array: Fruits: Apple, Grapes, Orange.
Instead of using implode function, you can achieve the same result by using foreach function, like this:
<?php // Create an indexed array of fruits $fruits = array("Apple", "Banana"); // Add a new fruit to the array $fruits[] = "Orange"; // Modify the second fruit $fruits[1] = "Grapes"; foreach ($fruits as $fruit_list) { echo $fruit_list . " "; } // Display the content of the updated array ?>
In the above code, we assign the value of the array $fruits to the variable $fruit_list, then print the contents of the array to the screen using the echo command. The quotation marks that are concatenated to the variable $fruit_list in the line of the echo construct (echo $fruit_list . ” “;) serve to leave space between the individual values of the array. So, the result will be: Apple Grapes Orange.
Looping through an array:
<?php // Create an indexed array of days of the week $daysOfWeek = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday"); // Loop through the array and display each day on a new line foreach ($daysOfWeek as $day) { echo "$day<br>"; } ?>
In this example, we have an indexed array of days of the week. We use a foreach loop to iterate through the array and display each day on a new line by using echo command and <br> HTML tag. So, the result of the above code will be:
Monday
Tuesday
Wednesday
Thursday
Friday
Multidimensional Array:
<?php // Create a multidimensional array of student grades $studentGrades = array( "Alice" => array("Math" => 95, "Science" => 88), "Bob" => array("Math" => 92, "Science" => 90) ); // Access and display Alice's Science grade echo "Alice's Science Grade: " . $studentGrades["Alice"]["Science"]; ?>
This example demonstrates a multidimensional array where student names are associated with an array of their subject grades. We access and display Alice’s Science grade, which is 88.