What is the shorthand for array notation in PHP?
I tried to use (doesn't work):
$list = {};
It will be perfect, if you give links on some information about other shorthands for PHP.
What is the shorthand for array notation in PHP?
I tried to use (doesn't work):
$list = {};
It will be perfect, if you give links on some information about other shorthands for PHP.
Update:
As of PHP 5.4.0 a shortened syntax for declaring arrays has been introduced:
$list = [];
Previous Answer:
There isn't. Only $list = array();
But you can just start adding elements.
<?php
$list[] = 1;
$list['myKey'] = 2;
$list[42] = 3;
It's perfectly OK as far as PHP is concerned. You won't even get a E_NOTICE for undefined variables.
E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array.
As for shorthand methods, there are lots scattered all over. If you want to find them just read The Manual.
Some examples, just for your amusement:
$arr[]
shorthand for array_push
.foreach
constructecho $string1, $string2, $string3;
+
elseif
$name = 'Jack'; echo "Hello $name";
YES, it exists!!
Extracted from another Stack Overflow question:
The shortened syntax for arrays has been rediscussed, accepted, and is now on the way be released with PHP 5.4
Usage:
$list = [];
Reference: PHP 5.4 Short Hand for Arrays
You can declare your array as follows:
$myArray1 = array(num1, num2, num3);
$myArray2 = array('string1', 'string2', 'string3');
$myArray3 = array( 'stringkey1'=>'stringvalue1', 'stringkey2'=>'stringvalue2');
$myArray4 = array( 'stringkey1'=>numValue1, 'stringkey2'=>numValue2);
$myArray5 = array( numkey1=>'stringvalue1', numkey2=>'stringvalue2');
$myArray6 = array( numkey1=>numValue1, numkey2=>numValue2);
You can have as many embedded arrays as you need.
The only way to define an array in php is by the array()
language construct. PHP doesn't have a shorthand for array literals like some other languages do.