Open In App

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:




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

Output:

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