You may ask, “How to create an empty array in PHP?” This is common in PHP codes, where you may want to store the values of a future computation into an array. You basically would declare the array as empty and store the computed values into it.
So, how can this be achieved?
PHP arrays with no value can be initialized in three ways:
- $myArray = array();
- $myArray = [];
- $myArray = (array) null;
Among the three methods shown, the most common among programmers is the second, which uses [].
This is because the second method is marginally faster as it is only a constructor and is just simpler to use.
Code
Let’s check out some code that uses the techniques listed above.
<?php
$empty1 = (array) null;
$empty2 = [];
$empty3 = array();
var_dump($empty1,$empty2,$empty3);
//All above array are empty and will return empty
//pushing values into second type of array
$empty[] ="traps" ;
$empty[] ="tracks" ;
$empty[] ="traces" ;
$empty[] ="traps" ;
var_dump ($empty) ;
?>