In PHP, you can use arrays to store a set of ordered data. The method of defining a PHP array is very simple. You can use the following two methods:
In PHP, you can use the array() function To define an array, the syntax is as follows:
$array = array(value1, value2, ...);
Among them, value1, value2, etc. are the elements in the array. The elements in an array can be of any data type, including strings, numbers, Boolean values, objects, and more.
The following is an example showing how to use the array() function to define an array containing strings and numbers:
$my_array = array("dog", "cat", 12, 23.5);
In the above example, $my_array is an array containing 4 elements Arrays, "dog", "cat", 12 and 23.5 respectively.
Another way to define an array is to use square brackets []. This method is more concise. The syntax is as follows:
$array = [value1, value2, ...];
The following is an example of using square brackets [] to define an array:
$my_array = ["apple", "banana", "orange"];
In the above example, $my_array is an array containing 3 elements, namely "apple", "banana" " and "orange".
It should be noted that using square brackets [] to define an array requires PHP version greater than or equal to 5.4, and in lower versions of PHP, only the array() function can be used to define arrays.
Summary
In PHP, you can use the array() function or square brackets [] to define an array. The syntax for using the array() function is $array = array(value1, value2, ...), while the syntax for using square brackets [] is $array = [value1, value2, ...]. The elements in an array can be of many types, including strings, numbers, Boolean values, objects, and more.
The above is the detailed content of How to define an array in php. For more information, please follow other related articles on the PHP Chinese website!