Home » PHP » PHP Arrays
This tutorial on PHP Arrays helps you learn what an array is and how you can create arrays. So, let us start.
An array stores multiple values, generally of the same type, in a single variable.
For example, in case you have a list of festivals that you want to store together, or maybe a list of stationery items, or a list of colors. In that case, you have an option to keep them in separate variables, but in this case, you will have to create a lot of variables, and they won't be related to each other.
In such a case, PHP arrays are used. This is because arrays can be used to store multiple values together in a single variable. You can use the foreach loop to traverse all the values stored in the array.
An array can be created in PHP using the array() function.
Syntax:
<?php
/* this function takes multiple values
separated by comma as input to create an aray */
array();
?>
There are three types of arrays in PHP:
Example:
<?php
/*
a simple array with car names
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");
?>
You can access the data stored in an array by either using the index numbers or using a foreach loop for traversing the array elements.
The index number for array elements starts from 0, i.e., the first element is at position 0, then the next element at position 1, the third element at position 3, and so on…
<?php
/*
a simple array with Lamborghini car names
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");
// print the first car name
echo $lamborghinis[0];
echo "Urus is the latest Super SUV by Lamborghini";
?>
Output:
Urus
Urus is the latest Super SUV by Lamborghini
Some of the advantages of using an array in our program/script:
You can store the data elements in an indexed array against numeric indexes. An index represents all the array elements. The index is a numeric value that starts from 0 for the first array element.
You can create an indexed array in PHP in two different ways. These are,
The syntax for the first way to create an indexed array:
<?php
/* 1st - direct array initialization */
$lamborghinis = array("Urus", "Huracan", "Aventador");
?>
The syntax for the second way to create an indexed array:
<?php
/* 2nd - distributed array initialization */
$suzuki[0] = "Swift";
$suzuki[1] = "Baleno";
$suzuki[2] = "Ertiga";
$suzuki[3] = "Brezza";
$suzuki[4] = "Vitara";
?>
Regardless of how much we initialize the array, the array can be accessed only as follows,
<?php
/*
Accessing array
*/
echo "Accessing the 2nd array...";
echo $suzuki[0], "n";
echo $suzuki[3], "n";
echo $suzuki[2], "n";
echo "Accessing the 1st array...";
echo $lamborghinis[1], "n";
echo $lamborghinis[0], "n";
echo $lamborghinis[2], "n";
?>
Output:
Accessing the 2nd array...
Swift
Brezza
Ertiga
Accessing the 1st array...
Huracan
Urus
Aventador
Therefore, for accessing an indexed array, we have to use the name of the array along with the element's index in square brackets.
Traversing an array means iterating it starting from the first index to the array's last element.
An indexed array can be traversed by either using a for loop or foreach. You can refer to the tutorials on PHP for and foreach loop to know their syntax and basic usage.
If you are using the for loop for traversing an indexed array, then you must know the size/length of the array. You can find it by using the count() function.
The syntax to traverse an array using the for loop is as follows.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// find size of the array
$size = count($lamborghinis);
// using the for loop
for($i = 0; $i < $size; $i++)
{
echo $lamborghinis[$i], "n";
}
?>
It is better to use foreach to traverse an indexed array in case you want to traverse the whole array. The reason is it does not require you to be bothered about calculating the array's size to loop around the array.
Here we have used the foreach for traversing the $lamborghinis array.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// using the foreach loop
foreach($lamborghinis as $lambo)
{
echo $lambo. "n";
}
?>
It is easier to use because of the numeric index values. Having numeric indexes is common to almost all programming languages; it makes the code more readable for others who go through your code.
It is similar to an indexed array. However, you can assign every value with a user-designed string type key rather than storing data sequentially with a numeric index.
You can create an associative array in two different ways; these are,
Syntax for the first way to create associative array:
<?php
/* 1st - direct array initialization */
$lamborghinis = array("suv"=>"Urus", "sports"=>"Huracan", "coupe"=>"Aventador");
?>
and the syntax for the second way to create associative array is:
<?php
/* 2nd - distributed array initialization */
$suzuki["hatch"] = "Swift";
$suzuki["utility"] = "Ertiga";
$suzuki["suv"] = "Vitara";
?>
Regardless of how much we initialize the array, we can access the array as follows,
<?php
/*
Accessing array
*/
echo "Accessing the 2nd array...";
echo $suzuki["hatch"], "n";
echo $suzuki["utility"], "n";
echo $suzuki["suv"], "n";
echo "Accessing the 1st array...";
echo $lamborghinis["suv"], "n";
echo $lamborghinis["sports"], "n";
echo $lamborghinis["coupe"], "n";
?>
Output:
Accessing the 2nd array...
Swift
Ertiga
Vitara
Accessing the 1st array...
Urus
Huracan
Aventador
Traversing an array means iterating it starting from the first index to the array's last element.
An associative array can be traversed either by using a for loop or foreach. You can check the PHP for and foreach loop tutorial for learning their syntax and basic usage.
To traverse an associative array when you are using the for loop, you must know the array's size/length, which you can find using the count() function.
Also, as the index in an associative array is neither numeric nor sequential, therefore for finding the index values or keys (because the data saved in the associative array is in the key-value form), the array_keys() function can be used for getting an array of the keys that are used in the associative array.
The syntax to traverse an array using the for loop is as follows.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// find size of the array
$size = count($lamborghinis);
// getting the array of keys/index strings
$keys = array_keys($lamborghinis);
// using the for loop
for($i = 0; $i < $size; $i++)
{
echo $lamborghinis[$keys[$i]] ." is a/an ". $keys[$i] ." car n";
}
?>
Output:
Urus is a/an suv car
Huracan is a/an sports car
Aventador is a/an coupe car
It is better to use foreach for traversing an associative array in case you want to traverse the whole array. Then, you are not required to bother about calculating the array's size to loop around the array.
Here the foreach loop has been used for traversing the $lamborghinis array.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// using the foreach loop
foreach($lamborghinis as $key => $value)
{
echo $value ."is a/an ". $key ." car n";
}
?>
Output:
Urus is a/an suv car
Huracan is a/an sports car
Aventador is a/an coupe car
The syntax is $key=>$value means in every iteration of the foreach, the array as key-value pair is represented.
Here are a few advantages of using an associative array in our program/script:
A multidimensional array is an array that stores another array at each index instead of storing a single value. It is an array of arrays.
Generally, you can store associative arrays inside multidimensional arrays.
Since it is an array of arrays, therefore it holds the associative arrays inside it.
Syntax for creating multidimensional array:
<?php
/* multidimensional array initialization */
$cars = array(
array(
"name"=>"Urus",
"type"=>"SUV",
"brand"=>"Lamborghini"
),
array(
"name"=>"Cayenne",
"type"=>"SUV",
"brand"=>"Porsche"
),
array(
"name"=>"Bentayga",
"type"=>"SUV",
"brand"=>"Bentley" )
, );
?>
Since an array inside an array is being dealt with here, to access any information, we first need to reach that array and, after that, get data from the particular array stored in the multidimensional array.
For instance, in case you want to display data for the Urus car, then first, you will have to get the first array inside your multidimensional array, which can be accessed using index 0. Then inside that array, you can display all the data, as was done in associative arrays.
<?php
/*
Accessing multidimensional array
*/
echo "Accessing multidimensional array...";
echo "Urus is an ".$cars[0]["type"]." manufactured by ".$cars[0]["brand"]."n";
echo "Bentayga is an ".$cars[2]["type"]." manufactured by ".$cars[2]["brand"]."n";
?>
Output:
Accessing multidimensional array...
Urus is an SUV manufactured by Lamborghini
Bentayga is an SUV manufactured by Bentley
Traversing an array means iterating it starting from the first index to the array's last element.
A multidimensional array can be traversed either by using two for loops or by using two foreach loops or one for loop and one foreach. You can check the PHP for and foreach loop tutorial to know their syntax and basic usage.
In a multidimensional array, you are required to traverse the main array and then traverse the arrays that are stored inside the main arrays; hence you need two loops.
If you are using the for loop for traversing a multidimensional array, then you should know the array's size/length, which you can find utilizing the count() function.
Let us consider the array defined above for the first example of traversing a multidimensional array.
<?php
/*
multidimensional array initialization
*/
$cars = array(
array(
"name"=>"Urus",
"type"=>"SUV",
"brand"=>"Lamborghini"
),
array(
"name"=>"Cayenne",
"type"=>"SUV",
"brand"=>"Porsche"
),
array(
"name"=>"Bentayga",
"type"=>"SUV",
"brand"=>"Bentley"
),
);
// array traversal
// find size of the array
$size = count($lamborghinis);
// using the for loop
for($i = 0; $i < $size; $i++)
{
foreach($cars[$i] as $key => $value) {
echo $key . " : " . $value . "n";
}
echo "n";
}
?>
Output:
name : Urus
type : SUV
brand : Lamborghini
name : Cayenne
type : SUV
brand : Prosche
name : Bentayga
type : SUV
brand : Bentley
In the multidimensional array above, the main array is an indexed array, and the arrays stored as elements are associative.
However, the main array can also be associative; let us take an example for it.
Also, as the index in an associative array is neither numeric nor sequential, therefore for finding the index values or keys(because the data saved in the associative array is in the key-value form), the function array_keys() can be used to get an array of the keys used in the associative array.
<?php
/*
multidimensional array initialization
*/
$cars = array(
"Urus" => array(
"type"=>"SUV",
"brand"=>"Lamborghini"
),
"Cayenne" => array(
"type"=>"SUV",
"brand"=>"Porsche"
),
"Bentayga" => array(
"type"=>"SUV",
"brand"=>"Bentley"
),
);
/*
array traversal
*/
// find size of the array
$size = count($lamborghinis);
// array keys
$keys = arra_keys($cars);
// using the for loop
for($i = 0; $i < $size; $i++)
{
echo $keys[$i]. "n";
foreach($cars[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "n";
}
echo "n";
}
?>
Output:
Urus
type : SUV
brand : Lamborghini
Cayenne
type : SUV
brand : Prosche
Bentayga
type : SUV
brand : Bentley
Some advantages of using a multidimensional array in our program/script: