PHP Arrays

In computer science, an array is a data structure that consists of multiple elements which are uniquely identified by the keys of the array. PHP arrays help manage data as a list.

Read Also: Find Array Length in PHP

Types of Arrays in PHP

There are three types of arrays in PHP, as mentioned below.

  1. Indexed array
  2. Associative array
  3. Multidimensional array

Must Read: How to Sort Array in PHP [Explained With Examples]

Indexed Array

In a PHP array, the index is represented by a number, and it starts from 0. We can store number, string, and object in the PHP array. By default, all PHP array elements are assigned to an index number.

There are different ways to define an indexed array.

$color=array(“Red”,“Green”,“Blue”,“White”);

$color[0]=“Red”;

$color[1]=“Green”;

$color[2]=“Blue”;

$color[3]=“White”;

Example

<?php  

$color=array("Red","Green","Blue","White");  

echo "Colors are: $color[0], $color[1], $color[2] and $color[3]";  

?>

Output

Colors are: Red, Green, Blue and White

Associative Array

We can associate the name with each element of the array in PHP using the ‘=>’ symbol.

There are two ways to define an associative array

// Method 1
$salary=array("Suman"=>"350000","Neha"=>"450000","Riya"=>"200000");
// Method 2
$salary = array();

$salary["Suman"]="350000";  

$salary["Neha"]="450000";  

$salary["Riya"]="200000";

Example

<?php    

$salary=array("Suman"=>"350000","Neha"=>"450000","Riya"=>"200000");    

echo "Suman salary: ".$salary["Suman"]."<br/>";  

echo "Neha salary: ".$salary["Neha"]."<br/>";  

echo "Riya salary: ".$salary["Riya"]."<br/>";  

?>

Output

Suman salary: 350000
Neha salary: 450000
Riya salary: 200000

Multidimensional Array

The multidimensional array is an array in which each element can also be an array. Each element in the sub-array can be an array or further contain an array within itself and so on.

Example

<?php
$marks = array(
    "Riya" => array (
      "physics" => 95,
      "maths" => 90,
    ),
    "Neha" => array (
      "physics" => 92,
      "maths" => 97,
    ),
);
echo "Marks for Riya in physics : " ;

echo $marks['Riya']['physics'] . "<br>";

echo "Marks for Neha in maths : ";

echo $marks['Neha']['maths'] . "<br>";

?>

Output

Marks for Riya in physics : 95
Marks for Neha in maths : 97

Read More: PHP Array Functions

Conclusion

These are the different types of arrays that are beneficial in learning PHP programming. We hope you have gained a basic understanding of PHP arrays. In case, you are facing some problems related to other concepts of PHP programming, do refer to our other blogs. 

Enjoy Programming 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *