Current Location: Home> Latest Articles> In-Depth Guide to PHP array() Function and Its Three Array Types Explained

In-Depth Guide to PHP array() Function and Its Three Array Types Explained

M66 2025-06-11

Introduction to the array() Function in PHP

In PHP, the array() function is used to create arrays. An array is a data structure that stores multiple values. PHP arrays are mainly divided into three types:

  • Indexed arrays: arrays with numeric indices
  • Associative arrays: arrays with named keys (strings) as indices
  • Multidimensional arrays: arrays that contain one or more arrays

Syntax

Syntax for creating an indexed array:

<span class="fun">array(value1, value2, ...);</span>

Syntax for creating an associative array:

<span class="fun">array(key1 => value1, key2 => value2, ...);</span>

Parameters

  • value — The value of the array element
  • key — The key (index) of the array element, optional

Return Value

The array() function returns an array composed of the parameters passed.

Example of Indexed Array

The following example shows how to create an indexed array and iterate through it to output its contents:

<?php
$products = array("Electronics", "Clothing", "Accessories", "Footwear");
$len = count($products);
for ($i = 0; $i < $len; $i++) {
    echo $products[$i];
    echo "<br>";
}
?>

Output:

Electronics
Clothing
Accessories
Footwear

Example of Associative Array

The example below demonstrates how to define an associative array and display its keys and values:

<?php
$rank = array("Football" => "1", "Cricket" => "2");
foreach ($rank as $mykey => $myvalue) {
    echo "Key = " . $mykey . ", Value = " . $myvalue;
    echo "<br>";
}
?>

Output:

Key = Football, Value = 1
Key = Cricket, Value = 2

Conclusion

This article provided a detailed explanation of the PHP array() function, covering the basic concepts and examples of indexed, associative, and multidimensional arrays. Understanding these is essential for handling data structures in PHP development. Hope this article helps you in your PHP learning journey.