Arrays are combined variables that allow us to store more than one value or a group of values
Indexed Arrays
Define an array
defines an array and each element value in the array is stored in the numeric index.
<?php
// Define an array
$colors = array("Red", "Green", "Blue");
print_r($colors);
?>
Numeric indexes are assigned automatically
Output:
Array
(
[0] => Red
[1] => Green
[2] => Blue
)
You can assign Indexes manually
<?php
$colors[5] = "Red";
$colors[1] = "Green";
$colors[10] = "Blue";
?>
Array types in PHP
There are three types of arrays that you can create.
- Indexed array - An array with a numeric key.
- Associative array: an array where each key has its own specific value.
- Multidimensional Array: An array that contains one or more arrays within itself.
Associative array
In an associative array, the keys assigned to the values can be arbitrary, user-defined strings.
#example.php
<?php
// Define an associative array
$ages = array("Syam"=>22, "Clark"=>32, "John"=>28);
?>
Multidimensional Arrays
The multidimensional array is an array in which each element can also be an array and each element in the sub-array can be an array or additionally contain an array within itself, etc.
#example.php
<?php
// Define a multidimensional array
$contacts = array(
array(
"name" => "Rathorji",
"email" => "testmail1@rathrji.in",
),
array(
"name" => "Rakesh",
"email" => "testmail2@rathrji.in",
),
array(
"name" => "Jhon",
"email" => "testmail3@rathrji.in",
)
);
// Access nested value
echo "Peter Rathorji's Email-id is: " . $contacts[0]["email"];
?>
Viewing Array Structure and Values
You can see the structure and values of an array by using one of two statements — var_dump() or print_r(). The print_r() statement, however, gives somewhat less information.
<?php
// Define array
$cities = array("India", "Nigeria", "England");
// Display the countries array
print_r($cities);
?>