Press "Enter" to skip to content

About Array in PHP

What is Array?

It is a special type of variable which can contain multiple values of the similar data type at the same time.

How to create an Array in PHP?

Arrays will be created using a function array(). Array() function can contain zero or more arguments. This function will return the new array which will be assigned to a variable using an assignment operator(=). If arguments are provided, they are used to initialize the array with data.

PHP arrays can grow and shrink dynamically as items are added and removed so it will not be needed to specify the array size at creation time.

How to create an empty array?

For creating an empty array, we can use array() function.

Now we will give an example for creating an empty array:

<html>
<body>
<?php
$a=array();
?>
</body>
</html>

How to create an array with values as arguments to the array() function?

Here we also use the function array(). And the array will be initialized by values.

Now we will give an example on Array with initialization:

<html>
<body>
<?php
$a=array("kolkata","Delhi","India");
?>
</body>
</html>

How many types of the array in PHP?

In PHP there are three types of Array. These are given below:

(i) Indexed Array
(ii) Associative Array
(iii) Multidimensional Array

What is an Indexed Array?

An Indexed Array is an array with a numeric index(Where a numeric value will specify index). Actually, the numeric index will start from 0.

How to create an Indexed Array?

We can create an Indexed Array in two ways.

(i) The index can be assigned automatically.
(ii) The index can be assigned manually.

Now we will give an example on two ways:

(i)

<html>
<body>
<?php
$a=array("amit","software","90000");//here the indexed array $a is containing three elements
?>
</body>
</html>

Here $a[0]=first array element value=”amit”
Here $a[1]=second array element value=”software”
Here $a[2]=third array element value=”90000”

(ii)

<html>
<body>
<?php
$a=array();
$a[0]="amit";
$a[1]="software";
$a[2]="90000";
?>
</body>
</html>

See also: