Shorthand array is the new feature added into PHP 5.4. This feature is not a vast improvement of PHP 5.4, but it is very effective way to represent array in PHP.
So, Today I am going to explain about the shorthand array in PHP with examples.Yes, I know it’s difficult to get used to with new syntax of the array in PHP.
Introduction
The array is the complex variables that store a group of values under a single variable name.Arrays can use either integers or strings for keys in PHP.PHP array is associative array which store element values in association with key values rather than in a strict linear index order and Before PHP 5.4, I am creating an array by using the array() construct which is the simplest way to create an array in PHP Whereas in PHP 5.4 offers us a special syntax like [1,2,3] which is called short hand array.PHP automatically converts key begins indexing at 0.
Let’s check out short hand array with the simple examples. Here, You will check both old and new version of the array in PHP by example.
Consider the following statement of array PHP < 5.4:
1 2 3 4 | $array = array(1,2,3); echo $array[2]; // OUTPUT : 3 |
Consider the following statement of array PHP 5.4:
1 2 3 4 | $array = [1,2,3]; echo $array[2]; //OUTPUT: 3 |
This newer version of syntax will give exactly the same result as the earlier version.To define an array using Short array syntax is very handy when you have a short list of known values.
This feature isn’t restricted to the number.You can also use associative key-value pair in short hand array also.
1 2 3 | $array = ['one' => 1, 'two' => 2, 'three' => 3]; |
Finally, as I have said earlier, Short array syntax is flexible than the previous syntax.This is useful if you’re using the array, try it out once. 🙂
I hope you have enjoyed this article, subscribe to our mailing list if you don’t want to miss any new article. Do Consider to share this article if you think this might be useful to other.