In addition to using array()
, we can also create an array by wrapping comma-separated elements in square brackets ([ ]
). This feature is sometimes referred to as short array syntax, and more closely resembles what you might see in other programming languages.
$number_array = [0, 1, 2];
In the code above, we created the variable $number_array
and assigned as its value an array containing the numbers 0
, 1
, and 2
. The number 0
is located at the 0th location index, the number 1
at the 1st, and the number 2
and the 2nd.
Let’s compare using short array syntax with invoking the array()
function:
$string_array = array("first element", "second element"); $str_arr_short = ["first element", "second element"]; $mixed_array = array(1, "chicken", 78.2, "bubbles are crazy!"); $mix_arr_short = [1, "chicken", 78.2, "bubbles are crazy!"];
Here, regardless of which method we used, we got the same results.
When constructing arrays, we can also place each element on its own line to make it easier to read:
$long_array = [ 1, 2, 3, 4, 5, 6 ];
Let’s practice creating some short syntax arrays!
Instructions
We’re going to create two arrays with the same elements.
- The first element should be “PHP”
- The second element should be “popcorn”
- The third element should be 555.55
Name the first array $with_function
and create it using the array()
function.
Now create the second array. Name it $with_short
, and create it using the short array syntax.
Reminder:
- The first element should be “PHP”
- The second element should be “popcorn”
- The third element should be 555.55