An array is used to store multiple values, generally of same type, in a single variable.
For example if you have a list of festivals that you want to store together, or may be a list of stationary items, or list of colors, then you can either keep them in separate variables, but then you will have to create a lot of variables and they won't be related to each other.
In such case, PHP arrays are used. Arrays can store multiple values together in a single variable and we can traverse all the values stored in the array using the foreach
loop.
We can create an array in PHP using the array()
function.
Syntax:
<?php
/*
this function takes multiple values
separated by comma as input to create
an aray
*/
array();
?>
In PHP there are 3 types of array:
Let's take a simple example for an array to help you understand how an array is created.
<?php
/*
a simple array with car names
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");
?>
To access the data stored in an array, we can either use the index numbers or we can use a foreach
loop to traverse the array elements.
Index number for array elements starts from 0
, i.e the first element is at the position 0
, the second element at position 1
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";
?>
Urus Urus is the latest Super SUV by Lamborghini
Here are a few advantages of using array in our program/script:
foreach
loop.