Current Location: Home> Latest Articles> How to Declare Arrays in PHP: Using Square Brackets and the array() Function

How to Declare Arrays in PHP: Using Square Brackets and the array() Function

M66 2025-09-21

PHP Array Declaration Methods

In PHP, arrays are used to store multiple values. There are two common ways to declare an array: the square bracket method and the array() function method.

Declaring Arrays Using Square Brackets

The square bracket method is the simplest way to declare an array. You simply enclose the array elements in square brackets and separate them with commas. For example:

$array = [1, 2, 3, 4, 5];

Declaring Arrays Using the array() Function

In addition to square brackets, you can also use the built-in array() function to declare arrays. Pass the elements as parameters to the function. For example:

$array = array(1, 2, 3, 4, 5);

Setting Key-Value Pairs in Arrays

PHP allows you to create associative arrays, where data is stored in key-value pairs. You can use the following syntax to set key-value pairs in an array:

$array['name'] = 'John Doe';

For example:

$array = [
    'name' => 'John Doe',
    'age' => 30
];

Accessing Array Elements

You can access array elements using square brackets or the array_get() function. For example:

$name = $array['name'];

Or:

$age = array_get($array, 'age');

Other Considerations for PHP Arrays

  • PHP arrays are ordered, meaning the order of elements matters.
  • Array elements can be of any data type.
  • Arrays can contain nested arrays.
  • PHP 7 introduced union types for arrays, allowing different data types to be stored in the same array.

With these two methods, you can easily declare and manipulate arrays in PHP. Mastering these basic array operations will help you become more efficient in PHP programming.