Difference between array() and [] in PHP

An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.

Syntax:

array(
    key  => value,
    key2 => value2,
    key3 => value3,
    ...
)

The comma after the last array element is not required can be omitted but this can help to understand other developers that the array is updated or not. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multiple line arrays, on the other hand, the trailing comma is commonly used, as it allows easier to add new elements at the end of the present array.



Note: Only the difference in using [] or array() is with the version of PHP you are using. In PHP 5.4 you can also use the short array syntax, which replaces array() with [].

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$array = array(
    "geek" => "tech",
    "tech" => "geek",
);
  
var_dump($array);
  
// As of PHP 5.4
$array = [
    "geek" => "tech",
    "tech" => "geek",
];
  
var_dump($array);
?>

chevron_right


Output:

array(2) {
  ["geek"]=>
  string(4) "tech"
  ["tech"]=>
  string(4) "geek"
}
array(2) {
  ["geek"]=>
  string(4) "tech"
  ["tech"]=>
  string(4) "geek"
}


My Personal Notes arrow_drop_up

COMPETITIVE PROGRAMMER

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.