PHP supports three types of arrays:
- Index array: an array with a numeric index.
- Associative array: an array with named keys.
- Multidimensional array: It contains one or more arrays in a specific array.
Note: Why is it always good to declare an empty array and then push items to that array?
Declare an empty array and start entering elements in it. With this, it prevents different errors due to array failure. It helps to get information about using bugs, rather than using arrays. It saves time during debugging. Most of the time, there may be nothing to add to the array when created.
Syntax for creating an empty array:
$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null;
When pushing elements to an array, you can use $emptyArray [] = "first". At this point, $emptyArray contains "first", use this command and send "first" to the array, which is declared empty at startup.
In other words, new arrays are initialized faster, using the syntax var first = [] instead of using the syntax var first = new Array(). The fact is that the constructor is the functions Array() and [] is part of the array literal syntax. Both are complete and performed in a completely different way. Both are optimized and are not affected by any overhead of calling functions.
Basic example of empty arrays:
<?php $emptyArray = (array) null; var_dump($emptyArray); ?>
Output:
array(0) { }
Now PHP 5.4, supports [] as an alternative, it is synonymous according to the compiler, and most PHP developers use $array = [] because it makes the round trip between JS and PHP easier.
<?php $firstempty = []; echo "Create the first empty array<br>"; $second = array( ); echo "Create a second empty array<br>"; $first = array( 1, 2); foreach( $first as $value ) { echo "Value is $value <br>"; } $first[0] = "one"; $first[1] = "two"; foreach( $first as $value ) { echo "Value is $value <br>"; } ?>
Output:
Create the first empty array Create a second empty array Value is 1 Value is 2 Value is one Value is two
Another way:
<?php $emptyArray=array(); array_push($emptyArray, "php", "Chinese", "website"); print_r($emptyArray); ?>
Output:
Array ( [0] => php [1] => Chinese [2] => website )