PHP: array() Function

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Example
Create an indexed array named $cars, assign three elements to it, and then print a text containing the array values:

<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>


Create an associative array named $age:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Prints: Peter is 35 years old.


Loop through and print all the values of an indexed array:

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

for($x=0;$x<$arrlength;$x++)
  {
  echo $cars[$x];
  echo "<br>";
  }
?>

Prints:
Volvo
BMW
Toyota


Loop through and print all the values of an associative array:

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

foreach($age as $x=>$x_value)
  {
  echo "Key=" . $x . ", Value=" . $x_value;
  echo "<br>";
  }
?>

Prints:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43


Create a multidimensional array:

<?php
// A two-dimensional array
$cars=array
  (
  array("Volvo",100,96),
  array("BMW",60,59),
  array("Toyota",110,100)
  );
  
echo $cars[0][0].": Ordered: ".$cars[0][1].". Sold: ".$cars[0][2]."<br>";
echo $cars[1][0].": Ordered: ".$cars[1][1].". Sold: ".$cars[1][2]."<br>";
echo $cars[2][0].": Ordered: ".$cars[2][1].". Sold: ".$cars[2][2]."<br>";
?>

Prints:
Volvo: Ordered: 100. Sold: 96
BMW: Ordered: 60. Sold: 59
Toyota: Ordered: 110. Sold: 100

Leave a Reply

Your email address will not be published. Required fields are marked *