An array is a data structure in PHP that stores multiple values in one memory location.
For example: If you want to store 50 numbers, then instead of defining 50 variables, it's easy to define an array of 50 lengths.
There are three types of arrays in PHP:
- Numeric array (Indexed array) - An array with a numeric index value.
- Associative array - Where each ID key is associated with a value of an array.
- Multidimensional array - Array containing one or more arrays.
Numeric Array
In an indexed array, the keys are numeric and start with 0, and the values can be any data type. The following shows two ways of assigning values to an indexed array:
Example:
<?php
$friends[0] = 'Jhon';
$friends[1] = 'Ramson';
$friends[2] = 'Nikita';
?>
or
Here I have used the array() function to create an array.
Example:
<?php
$friends = array('Jhon','Ramson','Nikita');
?>
Associative Array
Associative arrays are arrays that use named keys that you assign to them.
Example:
<?php
$salary['Jhon'] = 15000;
$salary['Ramson'] = 25000;
$salary['Nikita'] = 27000;
?>
or
<?php
$salary = array('John'=>15000, 'Ramson'=>25000, 'Nikita'=>27000);
?>
Multidimensional Array
A multidimensional array is an array that contains at least one other array as the value of one of the indexes.
Example:
<?php
$multiDArray = array(
"A" => array(0 => "red", 2 => "blue", 3 => "green"),
"B" => array(1 => "orange", 2 => "black"),
"C" => array(0 => "white", 4 => "purple", 8 => "grey")
);
echo $multiDArray["A"][3]; // Outputs green
echo "<br>";
echo $multiDArray["C"][8]; // Outputs grey
?>
Keep W3schools Growing with Your Support!
❤️ Support W3schools