Array types in PHP

Types of array:

In PHP, there are three types of arrays:

  • Indexed arrays – Arrays with numeric index
  • Associative arrays – Arrays with named keys
  • Multidimensional arrays – Arrays containing one or more arrays

 

Syntax how to define arrays:

1. Syntax for indexed arrays:

               array(value1,value2,value3,etc.);

2.  Syntax for associative arrays:

                 array(key=>value,key=>value,key=>value,etc.);
         3. Syntax for multidimensional arrays:
               array(array(),array(),array());

Example:

1. Indexed array:-

<!DOCTYPE html>

<html>
<body>
<?php
$arr=array(“Rohan”,”Mohan”,”Snaya”);
echo “Hi ” . $cars[0] . “and ” . $cars[2] . ” how  are you  both?” .””;
?>
</body>
</html>

Output will be : Hi Rohan and Snaya how are you both?

2. Associative  array:-

<!DOCTYPE html>

<html>
<body>
<?php
$age=array(“Rohan”=>”23″,”Snaya”=>”21″,”Mohan”=>”25”);
echo “Rohan is ” . $age[‘Rohan’] . ” years old.”;
?>
</body>
</html>

Output will be: Rohan  is 23 years old.

3. Multidimentional  array:-

<!DOCTYPE html>

<html>
<body>
<?php
$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>”;
?>
</body>
</html>

Output will be:   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 *