PHP Menu


Arrays in PHP


An array is a special variable, which can hold more than one value at a time. In other words, an array can hold many values under single name, and we can access the values by referring to an index .

In PHP, the array() function is used to create an array.

PHP supports three types of arrays, those are

  • Indexed array
  • Associative array
  • Multi-dimensional array

Indexed array :

In arrays, the elements are assigned to specific index to access those elements easily.In the Indexed array, index is represented by number which is starts from '0'.

An Indexed array is array with collection of elements where index is represented by number.

There are two ways to define indexed array, those are

1st-way:

$marks = array(60, 72, 66);

2nd-way:

$marks [0] = 60;
$marks [1] = 72;
$marks [2] = 66;

Example: "IndArray.php"


<html>

<head>
<title>Indexed Array</title>
</head>
<body>
<h1>Indexed Array Demo</h1>
<?php
$marks
=array(60,78,87,67);
echo 
"Marks are : $marks[0],$marks[1],$marks[2] and $marks[3]";
?>
</body>
</html>

Output :

image

Associative array :

The associative arrays are very similar to indexed arrays in terms of functionality but they are different in terms of their index.

Associative array will have their index as string so that we can establish a strong association between key and value. In PHP, we can associate name with each array element using "=>" symbol.

There are two ways to define associative array, those are

1st-way:

$marks = array("C"=>60, "Java"=>72, "Php"=>66);

2nd-way:

$marks ["C"] = 60;
$marks ["Java"] = 72;
$marks ["Php"] = 66;

Example: "AssocArray.php"


<html>

<head>
<title>Associate Array</title>
</head>
<body>
<h1>Associate Array Demo</h1>
<?php
$marks
=array("WT"=>56,"FLAT"=>67,"SE"=>65,"PPL"=>78);
echo 
"Marks of WT :".$marks["WT"]."<br/>";
echo 
"Marks of FLAT :".$marks["FLAT"]."<br/>";
echo 
"Marks of SE :".$marks["SE"]."<br/>";
echo 
"Marks of PPL :".$marks["PPL"]."<br/>";
?>
</body>
</html>

Output :

image

Multidimensional array :

The multidimensional array is also known as array of arrays. It allows you to store tabular data in an array.

Multidimensional array represents in the form of matrix(i.e. rows and columns).

The following way is to define multidimensional array

$employees = array (
				array (1,"A",28),
				array (2,"B",27),
				array (3,"C",29) 
				);

Example: "MultiArray.php"


<html>

<head>
<title>Multi-Dimensional Array</title>
</head>
<body>
<h1>Multi-Dimensional Array Demo</h1>
<?php
$students
=array(
            array(
501,"Kiran",20),
            array(
502,"Hari",21),
            array(
503,"Naveen",20)
            );
for(
$i=0;$i<3;$i++)
{
    for(
$j=0;$j<3;$j++)
    {
        echo 
$students[$i][$j]." ";
    }
    echo 
"<br/>";
}

?>
</body>
</html>

Output :

image
Next Topic :Strings in PHP