How to initilise or create array in PHP
There are two ways to initialize or create an array in PHP:
Using the array() function
The array() function takes a list of values as arguments and returns an array containing those values. The values can be of any type, including strings, numbers, other arrays, and objects.
Here is an example of how to use the array() function to initialize an array:
PHP
This will create an array containing the values 1, 2, 3, 4, and 5.
Using the [] syntax
Short array syntax is a newer way to initialize arrays in PHP. It is more concise and easier to read than using the array() function.
To use short array syntax, simply enclose the list of values in square brackets ([]).
Here is an example of how to use short array syntax to initialize an array:
PHP
$my_array = array(1, 2, 3, 4, 5);
This is equivalent to the following code:
PHP
$my_array = [1, 2, 3, 4, 5];
Which method should you use?
Either method is fine to use, but the short array syntax is generally preferred because it is more concise and easier to read.
Creating an empty array
To create an empty array, you can simply use [] or array().
PHP
$my_array = array(1, 2, 3, 4, 5);
Both of these will create an empty array.
$empty_array = [];
$empty_array = array();