An Array is a data structure that is used to store multiple values in a single variable.
Instead of creating different variables for each value, we can store all values together in an array.
Such type of structure makes data handling easy and organized that’s why it is called array.

PHP Arrays

In PHP, an array can store multiple values of same type or different types.
Each value in an array is identified by a key or index.

When we want to store a list of values and access them easily, we can use array structure.

PHP supports mainly three types of arrays:

  • Indexed Array
  • Associative Array
  • Multidimensional Array

Indexed Array:

In indexed array, each element is assigned an index number starting from 0.

Syntax:


$array_name = array(value1, value2, value3);

or


$array_name[0] = value1;
$array_name[1] = value2;

Example:


<?php
$colors = array("Red", "Green", "Blue");

echo $colors[0] . "<br/>";
echo $colors[1] . "<br/>";
echo $colors[2];
?>

The above program will print values using index number.

Associative Array:

In associative array, each element is assigned with a key instead of index number.

Syntax:


$array_name = array("key1" => value1, "key2" => value2);

Example:


<?php
$student = array("name" => "Rahul", "age" => 20);

echo $student["name"] . "<br/>";
echo $student["age"];
?>

The above program will print values using keys.

Multidimensional Array:

A multidimensional array is an array which contains one or more arrays inside it.

Syntax:


$array_name = array(
array(value1, value2),
array(value3, value4)
);

Example:


<?php
$marks = array(
array(50, 60),
array(70, 80)
);

echo $marks[0][0] . "<br/>";
echo $marks[1][1];
?>

The above program demonstrates accessing values from multiple dimensions.

Difference between Indexed and Associative Array

Indexed Array Associative Array
Uses numeric index Uses named keys
Index starts from 0 Keys are user defined
Access using index Access using key

Conclusion:

Array is very useful in PHP to store multiple values in a single variable.
It helps to manage data efficiently and reduces complexity of the program.