[wp-night-mode-button]

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.
[toc]

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.

$arrName = []

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:

 "Arpit",
    1=> "John",
    2=> "Mary",
    3=> "Ankur",
];
echo("Elements of array are:\n");
var_dump($arr);
?>
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.

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


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:

 "Arpit", 1=> "Jai", 2=> "Adithya");  // array with values

   echo("An array with three values: \n");
   var_dump($array);
?>

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.