8

does someone know the meaning of the [ ] in the creation of a PHP array, and if it's really needed. Becasuse from my point of view. Both ways are sufficinent

Way 1, with brackets:

$cars[] = array ('expensive' => $BMW,
                 'medium'    => $Volvo,
                 'cheap'     => $Lada);

Way2, without brackets:

$cars   = array ('expensive' => $BMW,
                 'medium'    => $Volvo,
                 'cheap'     => $Lada);
3
  • 5
    Way 1 and way 2 don't give the same result in fact. Commented Mar 28, 2015 at 7:18
  • What you mean? In my opinion both give a key-named array as result? Commented Mar 28, 2015 at 7:21
  • Use print_r() on the resulting variable to visualize the nesting difference. Commented Mar 28, 2015 at 7:22

6 Answers 6

10

Read http://php.net/manual/en/function.array-push.php for a clear answer as to the differences.

main differences:

  • citing array() can only be done when creating the variable.
  • $var[] can add values to arrays that already exist.
  • $var[] will create an array and is in effect the same function call as $var = array(...);

also

  • You can not assign multiple values in a single declaration using the $var[] approach (see example 4, below).

some work throughs:

1) Using array()

$cars = "cats";
$cars = array("cars","horses","trees");

print_r($cars) ;

Will output

$cars --> [0] = cars
          [1] = horses
          [2] = trees

2) Appending Values

Then writing $cars = array("goats"); will NOT append the value but will instead initialise a NEW ARRAY, giving:

 $cars --> [0] = goats

But if you use the square brackets to append then writing $cars[] = "goats" will give you :

 $cars --> [0] = cars
           [1] = horses
           [2] = trees
           [3] = goats 

Your original question means that whatever is on the right hand side of the = sign will be appended to current array, if the left hand side has the syntax $var[] but this will be appended Numerically. As shown above.

You can append things by key name by filling in the key value: $cars['cheap'] = $Lada; .

Your example 1 is setting that an array is held within an array, so to access the value $Lada you would reference $cars[0]['cheap'] . Example 2 sets up the array but will overwrite any existing array or value in the variable.

3) String And Numerical Indexing

The method of using the array(...) syntax is good for defining multiple values at array creation when these values have non-numeric or numerically non-linear keys, such as your example:

$cars = array ('expensive' => "BMW",
             'medium'    => "Volvo",
             'cheap'     => "Lada");

Will output at array of:

   $cars --> ['expensive'] = BMW
             ['medium'] = Volvo
             ['cheap'] = Lada

But if you used the alternative syntax of:

$cars[] = "BMW";
$cars[] = "Volvo";
$cars[] = "Lada";

This would output:

$cars --> [0] = BMW
          [1] = Volvo
          [2] = Lada

4) I'm still writing....

As another example: You can combine the effects of using array() and $var[] with key declarations within the square brackets thus:

$cars['expensive'] = "BMW";
$cars['medium'] = "Volvo";
$cars['budget'] = "Lada";

giving:

   $cars --> ['expensive'] = BMW
             ['medium'] = Volvo
             ['cheap'] = Lada

(my original answer was verbose and not very great).

5) Finally.....

So what happens when you combine the two styles, mixing the array() declaration with the $var[] additions:

$ray = array("goats" => "horny", "knickers" => "on the floor", "condition" => "sour cream");
$ray[] = "crumpet";
$ray[] = "bread";

This will maintain both numeric and string key indexes in the array, outputting with print_r():

$ray --> [goats] => horny
         [knickers] => on the floor
         [condition] => sour cream
         [0] => crumpet
         [1] => bread
Sign up to request clarification or add additional context in comments.

3 Comments

bloody hell, I just rewrote my answer as my original answer wasn't very good and it gets a tick and +2 . I hope my rewrite also lives up to these expectations, now!
@Krooy_mans no worries, I have added a further example of mixing syntax :-)
Unfortunately, I can't upvote again ;-). Cheers, have a good one!
3

They are different. The first one is an array inside of another one

$cars[] = array ('expensive' => "BMW",
             'medium'    => "Volvo",
             'cheap'     => "Lada");

var_dump($cars);

array (size=1)
 0 => 
  array (size=3)
   'expensive' => string 'BMW' (length=3)
   'medium' => string 'Volvo' (length=5)
   'cheap' => string 'Lada' (length=4)

The second one is just an array

$cars   = array ('expensive' => "BMW",
             'medium'    => "Volvo",
             'cheap'     => "Lada");

var_dump($cars);

array (size=3)
 'expensive' => string 'BMW' (length=3)
 'medium' => string 'Volvo' (length=5)
 'cheap' => string 'Lada' (length=4)

Comments

2

way 1 results an array with array values (array of array) whereas way2 is array which contains mentioned values

Comments

1

Way 1 adds your new array() at the end of the existing array. So if you have 2 elements inside that array already, a third one with the array you specified will be created.

Way 2 is the typical array creation - just that some other variables are used to fill the fields.

Simply to complete your exercise, here is way 3:

$arr = array();
$arr[1] = array("foo"=>"bar");

This puts the foo:bar array at entry #1 into the $arr variable.

Comments

0

The second example is clear. In the first example you are adding an array element without specifying its key, hence the empty brackets []. As the array is not yet initialized, its created at the same time. The result is, as others already pointed out, a multidimensional array.

Beware though that the first way is not encouraged:

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.

If $cars was already set, e.g. to a string, you would get an error.

$cars = 'test';
$cars[] = array ('expensive' => $BMW,
                 'medium'    => $Volvo,
                 'cheap'     => $Lada);

Comments

0

Method 1, with brackets: Multidimensional array

Array ( [0] => Array ( [expensive] => 12 [medium] => 13 [cheap] => 14 ) ) 

Method 2, with brackets: Associative array

Array ( [expensive] => 12 [medium] => 13 [cheap] => 14 ) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.