Types of Arrays in PHP with examples

Types of Arrays in PHP

In PHP, arrays are essential data structures that allow you to store multiple values in a single variable. PHP arrays are actually ordered maps, acting as both vectors and hash tables. There are three main types of arrays in PHP: 

  • Indexed Arrays
  • Associative Arrays
  • Multidimensional Arrays

1. Indexed Arrays

In PHP, An indexed array is a type of array where each element is assigned a numeric index, starting from 0 by default. The index automatically increases for each subsequent element. These arrays are ideal for storing ordered lists of items.

Example:

<?php 
$cars = array("Volvo", "BMW", "Toyota"); 
?>

2. Associative Arrays

Associative arrays use named keys that you define, instead of numerical indexes. These keys are used to access specific values.

Example:

<?php
$person = array("name" => "John", "age" => 30);
?>

3. Multidimensional Arrays

Multidimensional arrays are arrays that contain one or more arrays as elements. They are used for more complex data structures.

<?php
$contacts = array(
    array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
    ),
    array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
    )
);

// Accessing nested value
echo "Peter Parker's Email: " . $contacts[0]["email"];

?>

Output:

Peter Parker’s Email: peterparker@mail.com