In this article, we’ll cover the basics of PHP arrays along with some advanced concepts. We’ll start by introducing you to what an array is, before moving on to the basic syntax of arrays and the different types of indexes available.
Introduction to PHP Arrays
PHP arrays are powerful data structures that allow developers to store and manipulate collections of values. An array is a variable that can hold multiple values, each identified by a unique key or index value.
Arrays in PHP can be used in many ways, such as storing user input, accessing file system directories and files, managing database results and much more. With built-in functions for sorting, searching, filtering and transforming arrays, working with them in PHP is easy.
Basic Concepts: What is an Array?
An array is a collection of variables grouped under one name. It allows the developer to store multiple pieces of data (values) under one variable name instead of creating individual variables for each element.
The array()
function accepts any number of comma-separated values. The values contained within an array can be of different data types such as integers, strings, Booleans or even other arrays.
Basic Syntax: Creating and Accessing Arrays
To create an array in PHP, we use the following syntax:
$array_name = array(value1,value2,...);
Here’s an example of creating a simple indexed array containing three elements (numbers):
$num_array = array(14, 25, 36);
We can access individual elements in an indexed array by their position (or index) within the array. In PHP (and many other programming languages) arrays are zero-indexed, meaning that the first element starts at position zero and not one. To access a particular element by its index, we simply reference it like this:
echo $num_array[0];
// Output: 14
In this example, we’re accessing the first element of $num_array
by its index, which is zero.
Types of Indexes in PHP Arrays
PHP arrays can have different types of indexes. The most commonly used are indexed and associative arrays.
Indexed arrays
An indexed array uses numeric indices to access and store values in an array. Here’s an example:
$colors = array('red', 'blue', 'green'); echo $colors[0];
// Outputs: red
The above code creates an indexed (numerically keyed) array containing three elements/colors. We can easily access each element/color using its corresponding index within square brackets as shown above.
Associative arrays
On the other hand, associative arrays use named keys/indices instead of numerical ones to store data. This makes it easier for developers to retrieve values according to the keys they set.
Here’s an example:
$user_data = array( 'name' => 'John Doe', 'email' => 'johndoe@example.com', 'age' => 30 );
echo $user_data['name'];
// Outputs: John Doe
In the code above, we have an associative array with three key–value pairs. We can access data from this array by using the corresponding key name.
Popular Questions about PHP Arrays
Here are ten of the most popular questions beginning web developers ask about PHP arrays and their answers.
How do I add elements to an existing PHP Array?
You can add elements to an existing PHP indexed or associative array using the array_push()
or []
(square bracket) notation. Using array_push()
, we can append one or more values to the end of an array.
Here’s an example:
$fruits = array('apple', 'orange'); array_push($fruits, 'banana', 'grape');
print_r($fruits);
// Output: Array ([0] => apple [1] => orange [2] => banana [3] => grape)
In this code snippet, we have added two new elements (banana
and grape
) to the existing $fruits
array using the array_push()
.
Alternatively, you can use square brackets notation by assigning a value to a new index position in an indexed array or setting a new key–value pair for associative arrays.
For example, to add element to indexed arrays, $num_array[] = 67;
will add the value 67
at the end of the $num_array
.
As an example of adding an element to an associative array, $user_data['country'] = 'United States';
will add a new key–value pair to the $user_data
array.
How do I remove elements from an existing PHP Array?
You can remove elements from an existing PHP array using the unset()
function or the array_splice()
function. Using the unset()
function, you can remove a specific element of an indexed or associative PHP array by specifying its index or key respectively.
Here’s an example code snippet:
$fruits = array('apple', 'orange', 'banana', 'grape');
unset($fruits[2]);
print_r($fruits);
// Output: Array ([0] => apple [1] => orange [3] => grape)
In this example, we’ve removed the third element (banana
) of the $fruits
array using the unset()
function.
Alternatively, you can use the array_splice()
function to remove a range of elements from an indexed array. To remove a key–value pair from an associative array, you can also use the unset()
function by specifying the key that you want to remove.
Here’s an example code snippet:
$user_data = array(
'name' => 'John Doe',
'email' => 'johndoe@example.com',
'age' => 30,
'country' => 'United States'
);
unset($user_data['country']);
print_r($user_data); // Output: Array ( [name] => John Doe [email] => johndoe@example.com [age] => 30 )
In this code snippet, we have removed the 'country'
key–value pair from the $user_data
associative array using the unset()
function.
How do I check if a value exists in an array in PHP?
You can check if a value exists in an array in PHP by using the in_array()
function. The in_array()
function searches for a given value in an array, and returns true if the value is found and false otherwise.
Here’s an example code snippet:
$fruits = array('apple', 'orange', 'banana', 'grape');
if (in_array('apple', $fruits)) { echo 'Apple is in the fruits array'; } else { echo 'Apple is not in the fruits array'; }
// Output: Apple is in the fruits array
In this example, we’ve used the in_array()
function to check if the value apple
exists in the $fruits array. Since apple
is present in the array, the condition evaluates to true and the message Apple is in the fruits array
is outputted. If apple
was not present in the array, the message Apple is not in the fruits array
would have been outputted instead. The in_array()
function is case-sensitive, so apple
and Apple
would be treated as two different values. If you want a case-insensitive search, you can use the array_search()
function instead.
How do I remove elements from an existing PHP array?
You can remove elements from an existing PHP array using the unset()
function or the array_splice()
function. Using the unset()
function, you can remove a specific element of an indexed or associative PHP array by specifying its index or key respectively. Alternatively, you can use the array_splice()
function to remove a range of elements from an indexed array.
To remove a range of elements from an indexed array using the array_splice()
function, you need to specify the starting index and the number of elements to remove.
Here’s an example code snippet:
$fruits = array('apple', 'orange', 'banana', 'grape'); array_splice($fruits, 1, 2);
print_r($fruits);
// Output: Array ( [0] => apple [3] => grape )
In this example, we’ve removed the elements at indices 1 and 2 (i.e., orange
and banana
) from the $fruits
array using the array_splice()
function.
To remove a key–value pair from an associative array using the unset()
function, you can provide the key of the element you want to remove as the argument.
Here is an example code snippet:
$user_data = array( 'name' => 'John Doe', 'email' => 'johndoe@example.com', 'age' => 30, 'city' => 'New York' );
unset($user_data['city']);
print_r($user_data);
// Output: Array ( [name] => John Doe [email] => johndoe@example.com [age] => 30 )
This code snippet shows how to remove the city
key–value pair from the user_data
associative array using the unset()
function.
How do you loop through a PHP array?
To loop through a PHP array, you can use a foreach
loop like this:
foreach ($array as $key => $value) {
// Code to be executed for each element of the array
}
In the above code, $array
is the name of the array you want to loop through. $key
and $value
are variables that will hold the key and value of the current element of the array, respectively. You can then use these variables to perform some action for each element of the array.
How do you sort a PHP array?
Sorting is a common operation when working with arrays in PHP. The following are some of the functions you can use to sort arrays:
sort()
: sorts the values of an array in ascending orderrsort()
: sorts the values of an array in descending orderasort()
: sorts an associative array in ascending order, according to the valuearsort()
: sorts an associative array in descending order, according to the valueksort()
: sorts an associative array in ascending order, according to the keykrsort()
: sorts an associative array in descending order, according to the key
How to create a multidimensional array in PHP?
To create a multidimensional array in PHP, you simply create an array of arrays.
Here’s an example:
$multi_array = array( array("apple", "orange"), array("banana", "grape"), array("peach", "plum") );
In the above example, we’ve created a multidimensional array with three arrays, each containing two elements.
Appending Elements to a PHP Array
You can append elements to a PHP array using the []
operator or the array_push()
function.
Using the []
operator
Here’s an example of appending elements to an array using the []
operator:
$countries = array("India", "USA", "UK"); $countries[] = "China"; $countries[] = "Russia";
// $countries now contains: array("India", "USA", "UK", "China", "Russia")
In the code above, we first create an array called $countries
with three elements. We then append two more elements to the array using the array[]
operator.
Using the array_push()
function
Here’s an example of appending elements to an array using the array_push()
function:
$countries = array("India", "USA", "UK"); array_push($countries, "China", "Russia");
// $countries now contains: array("India", "USA", "UK", "China", "Russia")
In the above code, we first create an array called $countries
with three elements. We then append two more elements to the array using array_push
.
Conclusion
This article has covered some of the most frequently asked questions related to PHP arrays.
Arrays are an essential data structure in PHP, allowing developers to store and manipulate collections of data easily. We’ve learned how to create, add elements to, remove elements from, and loop through arrays in PHP. By using multidimensional arrays, we can organize data into multiple dimensions or layers, and a vast range of built-in functions are available to manipulate and traverse arrays.
Remember, PHP arrays don’t have to be indexed numerically: they can also be associated with keys. We can use these keys to associate values with specific pieces of data, allowing us to retrieve and manipulate specific items easily.
Matt is the co-founder of SitePoint, 99designs and Flippa. He lives in Vancouver, Canada.