PHP arrays are a variable that holds more than one value within a single variable. Generally, the element of the array will be of the same data type.
Associative array:
It is also an array in which each key is associated with a value.Multidimensional array:
It is an array containing more than one array.There are two ways to represent PHP arrays. These are:
[
and ]
Let us see the associated example.
Source Code
<?php
$array = array('Apple', 'Banana', 'Orange', 'Mango');
var_dump($array);
$array = ['Apple', 'Banana', 'Orange', 'Mango'];
var_dump($array);
?>
An indexed or numeric array is very useful for storing each array element with a numeric index. By default array index starts from 0
indexes and the last element index number is (array length-1)
.
To create an indexed array, pass multiple values inside the PHP array()
function and separate each value with a comma ,
.
Source Code
<?php
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
$fruits[0] = 'Apple';
$fruits[1] = 'Banana';
$fruits[2] = 'Orange';
$fruits[3] = 'Mango';
?>
Remember: Indexes start from 0, not 1.
Index array element can be access through: $arrayName[index]
Source Code
<?php
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
echo "First Fruit is $fruits[0]" . '<br>';
echo "Second Fruit is $fruits[1]" . '<br>';
echo "Third Fruit is $fruits[2]" . '<br>';
echo "Forth Fruit is $fruits[3]" . '<br>';
?>
PHP associative array has named keys that contain the values.
Creating an associative array using two ways:
1:An associative array can be created using the array()
function or []
.
Source Code
<?php
$fruit = array(
'mango' => 22,
'orange' => 25,
'apple' => 30
);
?>