Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Dec 2010
    Posts
    24
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Arrow Initializing Arrays

    I have seen arrays in PHP initialized in the following ways:

    $some_array1 = ...
    $some_array2[] = ...

    What's the difference between initializing arrays in these ways? Why do some require [] brackets and others don't?

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Both are valid. Neither will throw an error in PHP assuming that $some_array2 isn't already in use as a scalar value.
    PHP Code:
    $a1 = array(); // valid
    $a2 = []; // valid 5.4+
    $a3[] = 'a val'// valid 
    $a4 = array('a val'); // valid

    $a5 = new stdclass;
    $a5[] = 'val'// invalid.

    $a6 'string';
    $a6[] = 'string'// invalid 
    Typically I use $a = array(); since its clear its an array.

  • #3
    New Coder
    Join Date
    Dec 2010
    Posts
    24
    Thanks
    7
    Thanked 0 Times in 0 Posts
    PHP Code:
    $a3[] = 'a val'// valid 
    So this means if I want to define an array with both an index and a value, I need to use the brackets next to the variable's name, right?


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •