Short Hand Array in PHP

  • Avinash
  • 0
  • Mar 12, 2012
  • Web Development

In previous article, you can find this features as a newly added feature in PHP 5.4. We can say that, this is not much big improvement for developers but this features has made PHP in paraller with other languages.

But still we can say that array(1,2,3) also a much easier to create an array. In short hand array we can create a new array just like [1,2,3].

So here not much to explain to going to example directly.

We will go throught both old and new version of declaring the array in PHP and using the same.

Array Before PHP 5.4

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

Array with PHP 5.4

$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
    $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

Conclusion

So based on above example we can write below condition:

array(1,2,3) = [1,2,3]; // Note: // Above line can not be used in real code. // This is just for demonstration
    array(1,2,3) = [1,2,3];
    // Note:
    // Above line can not be used in real code.
    // This is just for demonstration

Related Posts

Written by Avinash

Avinash Zala currently working at a leading web development company as a Sr. PHP Web Developer. He is the founder of the Xpert Developer. He has completed B.E. in Information Technology. Born and brought up in Ahmedabad. He loves to code and coding is all about passion for him. Follow him on twitter at Avinash Zala & Xpert Developer.

View all posts by: