PHP tutorial-Array


PHP Array


Array is a collection of homogeneous values. There are three types of array are commonly used in PHP. They are one-dimensional array, associative array, and two-dimensional array.

One-dimensional array

A one-dimensional array stores its elements sequentially. You can use the syntax below to create a one-dimensional array in PHP.


$arr=array(val1,val2,val3,val4);


or


$arr[0]=val1;
$arr[1]=val2;
$arr[2]=val3;
$arr[3]=val4;


This will create an array of four elements (val1,val2,val3,val4).
 
Example:
<html>
<body>
 
<?php
$arr=array(1,2,3,4);
echo $arr[0].$arr[1].$arr[2].$arr[3]; /*accessing 1d-array elements */
?>
 
</body>
</html>

Associative array

Each element of the associative array contains Key or ID and Value. Before the => symbol, it is the key and after the symbol, it is the value of one element of the assocative array.

Example:

<html>
<body>
 
<?php
$arr=array("index0"=>1,"index1"=>2,"index2"=>3,"index3"=>4);
echo $arr["index0"].$arr["index1"].$arr["index2"].$arr["index3"];
//accessing associative array elements
?>
 
</body>
</html>

Multi-dimensional array

A multi-dimensional array stores values in rows and columns. It is similar to the associative array except that each value of the element is an array.
 

Index 

0

1

2

Set1

1

2

3

Set2

4

5

6

 
Example:
<html>
<body>
 
<?php
$darr=array
(
 "set1"=>array(1,2,3),
 "set2"=>array(4,5,6)
);
 
echo $darr["set1"][0];// accessing 2d-array elements
?>
 
</body>
</html>



Comments





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.