{Quality Online Education Since 2009}

PHP Arrays

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 its easy to define an array of 50 length.

There are three types of arrays in PHP:

Numeric Array

In an indexed array, the keys are numeric and starts 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 array() function to create 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
?>