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.
Table of Contents
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.
1 2 3 |
$arrName = [] |
Example
1 2 3 4 5 6 7 8 |
<?php $emptyArr = []; echo("An empty array in PHP is: \n"); var_dump($emptyArr); ?> |
Output
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $arr = []; echo("An empty array in PHP is: \n"); var_dump($arr); $arr = [ 0=> "Arpit", 1=> "John", 2=> "Mary", 3=> "Ankur", ]; echo("Elements of array are:\n"); var_dump($arr); ?> |
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.
1 2 3 |
array($index1 => $value1, $index2 => $value2, ...,$indexN => $valueN); |
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
1 2 3 4 5 6 7 8 |
<?php $emptyArr = array(); echo("An empty array in PHP: \n"); var_dump($emptyArr); ?> |
Output
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $array = array(); echo("An empty array in PHP: \n"); var_dump($array); $array = array(0=> "Arpit", 1=> "Jai", 2=> "Adithya"); // array with values echo("An array with three values: \n"); var_dump($array); ?> |
Output
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.