Which of the following is the correct way to create an associative array in PHP?

Creating Associative Arrays in PHP

In PHP, one of the versatile data structures in use is the Associative Array. Unlike indexed arrays that use numeric keys, associative arrays allow developers to use string keys which offers better readability and ease of access when managing data.

The correct syntax to create associative arrays can be seen in two ways as shown from the correct answers to the quiz.

The Short Array Syntax

The short array syntax was introduced in PHP 5.4. It uses the square brackets, and the => operator to map keys to values. Here’s how to declare an associative array using the short array syntax:

$array = ['key' => 'value']; 

The Array() Function

The traditional method or long array syntax, uses the array() function to create an array. In an associative array, the => operator is used to map keys to values:

$array = array('key' => 'value');

In both cases, 'key' is the named index or key to the array, and 'value' is the associated data matching the key.

Practical Example

Let's say you want to create an associative array to hold a person’s information. Here's how you’d do it using both syntaxes:

$person = ['name' => 'John', 'age' => 25, 'profession' => 'Engineer']; // short array syntax

$person = array('name' => 'John', 'age' => 25, 'profession' => 'Engineer'); // traditional method

In these arrays, 'name', 'age', and 'profession' are keys whereas 'John', 25, and 'Engineer' are the corresponding values.

Using named keys in associative arrays make it intuitive and straightforward to access and manipulate data. For instance, to access the person's name, you'd use $person['name'], and it would return 'John'.

Key Takeaway

While both syntaxes are correct and currently supported, it's recommended to use the short array syntax ([]) asn it makes the code cleaner and more readable.

Remember that in PHP associative arrays, keys are unique, meaning each key can only appear once in an array. If you attempt to add a value to an existing key, it will override the existing value instead of adding a new one.

Do you find this helpful?