- An array stores value under a common name.
- An array is a variable that can hold more than one value at a time.
Create an Array in PHP
- In PHP, array() function is used to create the array
- Arrays in PHP can be divided into three,
- Indexed Arrays
- Associative arrays
- Multidimensional Arrays
PHP Indexed Arrays
- Indexed Arrays are the arrays with numeric syntax.
- There are two ways to create an indexed array.
- Assigned automatically
- Assigned manually
Assigned automatically
$numbers = array("One", "Two", "Three");
Assigned manually
$numbers[0] = "One";
$numbers[1] = "Two";
$numbers[2] = "Three";
PHP Associative Arrays
- Associative arrays are the arrays with named keys.
- There are two ways to create associative arrays.
$numbers = array("number1"=>"1", "number2"=>"2", "number3"=>"3");
Or
$numbers['number1'] = "1";
$numbers['number2'] = "2";
$numbers['number3'] = "3";
PHP Multidimensional Arrays
- A multidimensional array is an array of arrays or containing one or more arrays.
- A two-dimensional array is an array of arrays.
- A three-dimensional array is an array of arrays.
<?php
$vehicles = array
(
array("Sumo",10,20),
array("Tata",15,20),
array("Nano",20,30)
);
echo $vehicles[0][0].": Sold: ".$vehicles[0][1].", In stock: ".$vehicles[0][2].".<br>";
echo $vehicles[1][0].": Sold: ".$vehicles[1][1].", In stock: ".$vehicles[1][2].".<br>";
echo $vehicles[2][0].": Sold: ".$vehicles[2][1].", In stock: ".$vehicles[2][2].".<br>";
?>