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:
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>
The array() function returns an array composed of the parameters passed.
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
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
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.