$myArray = []; 

Creates empty array.

You can push values onto the array later, like so:

$myArray[] = "tree";
$myArray[] = "house";
$myArray[] = "dog";

At this point, $myArray contains "tree", "house", and "dog". Each of the above commands is added to the array, storing the elements that were already there.


Why it is always good practice to declare an empty array and then push the items to that array?

When you declare an empty array and then begin storing elements into it later. With the help of this, you can avoid different errors due to faulty array. It helps to have the buggy usage data, instead of having the array. Save time while debugging. Most of the time, you may not have anything to add to the array at creation time.


Syntax to create an empty array:

$emptyArray = []; 
$emptyArray = array();
$emptyArray = (array) null;


The empty square brackets syntax for appending to an array is simply a way of telling PHP to assign the indexes to each value automatically


#example

$myArray[0] = "tree";
$myArray[1] = "house";
$myArray[2] = "dog";


You can assign indexes yourself if you want, and you can use any numbers you want. You can also assign index numbers to some items and not others.

#example

$myArray[10] = "tree";
$myArray[20] = "house";
$myArray[] = "dog";

Now PHP 5.4, which supports [] as an alternative, As per the compiler concerned it was synonymous and most of the PHP developers uses $array = []

<?php 

/* method to create Empty array. */
$firstempty = []; 
echo "Created First empty array "; 
 
/* method to create Second Empty array. */
$second = array( ); 
echo "Created second empty array"; 
 
/* First method to create array. */
$first = array( 1, 2); 
  
foreach( $first as $value ) { 
 echo "Value is $value "; 
} 
  
/* Second method to create array. */
$first[0] = "one"; 
$first[1] = "two"; 
  
foreach( $first as $value ) { 
 echo "Value is $value "; 
} 
?> 

output

Best way to initialize empty array in PHP


Another Method:

<?php 

// Create an empty array 
$emptyArray=array(); 

// Push elements to the array 
array_push($emptyArray, "we", "are", "looking"); 

// Display array elements 
print_r($emptyArray); 
?> 

Thanks for visiting us !