Last Updated: February 25, 2016
·
9.41K
· moak

PHP 5.4 Shorthand for Arrays

I know most people will already now this, but I can't believe I missed the memo :D

//regular array notation
$my_array = array(1,2,3);
echo $my_array[2]; // 3

//new array short hand
$my_array = [1,2,3];
echo $my_array[2]; // 3

$my_array1 = ["element"=>1,2,3,"new_key"=>4];
echo $my_array1["element"]; // 1

$my_array1 = ["element"=>"value",2,3,"new_key"=>4];
echo $my_array1["element"]; // value

Watch out though, this is not backwards compatible, so probably not ready yet for most budget shared hosting solutions. However if you are already using other PHP 5.4 features and know what you are doing,

http://www.xpertdeveloper.com/2012/03/php-short-hand-array/