Declare empty array in php

How to initialize empty array in PHP

An array is a data structure where you can store the same or different types of data in a single variable.

In PHP, you can declare empty array using square brackets ([]) or using array() function.

Using square brackets to declare empty array in PHP

The below syntax can declare empty array in PhP. We can also adding the elements to this array using square brackets.

Example

Output

An empty array in PHP is:

array(0) {
}

Code Explanation

In the above program, we have declared empty array using [] and printed it using var_dump.

You can add elements in array with the help of square brackets as below:

An empty array in PHP is:
array(0) {
}
Elements of array are:
array(4) {
[0]=>
string(5) “Arpit”
[1]=>
string(4) “John”
[2]=>
string(4) “Mary”
[3]=>
string(5) “Ankur”
}

Here, we have added elements to empty array using square brackets([]).

Using array() to declare empty array in PHP

The below syntax can also declare empty array in PHP.

An array function has N parameters, where N is the number of elements the array stores. $index1, $index2, …, $index is an index of array elements and can be an integer or string. $value1, $value2, …, $valueN is the value of array elements.

Example

Output

An empty array in PHP:

array(0) {
}

Code Explanation

The above program shows how we can use the array() function to initialize an empty array in PHP.

We can use array() function to add elements into the array in PHP.
Here is an example:

Output

An empty array in PHP:

array(0) {
}
An array with three values:
array(3) {
[0]=>
string(5) “Arpit”
[1]=>
string(3) “Jai”
[2]=>
string(7) “Adithya”
}

From the above, we have learned how to declare empty array using square brackets([]) and an in-built PHP function array().

That’s all about how to declare empty array in PHP.

Was this post helpful?

Leave a Reply

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