• Home
  • What is the difference between indexed array and associative array?

What is the difference between indexed array and associative array?

In PHP, an array is a data structure that stores a collection of values. There are two types of arrays in PHP: indexed arrays and associative arrays.

An indexed array is a type of array that stores a collection of values that are accessed using numeric indices. The indices are 0-based, meaning that the first element has an index of 0, the second element has an index of 1, and so on. Indexed arrays are useful for storing and accessing simple lists of data, such as lists of numbers, dates, or names.

Here is an example of an indexed array in PHP:

$colors = array('red', 'green', 'blue');

echo $colors[0]; // Outputs "red"
echo $colors[1]; // Outputs "green"
echo $colors[2]; // Outputs "blue"

In this example, the $colors array has three elements with indices 0, 1, and 2. The elements can be accessed using the array indices in square brackets.

An associative array is a type of array that stores a collection of values that are accessed using string keys. The keys are used to identify the elements, and can be any string value. Associative arrays are useful for storing and accessing data that is more complex and structured than simple lists of values. They are often used to store data that has an inherent meaning, such as the data for a person object (e.g. name, age, gender) or a product object (e.g. name, price, quantity).

Here is an example of an associative array in PHP:

$person = array('name' => 'John', 'age' => 30, 'gender' => 'male');

echo $person['name']; // Outputs "John"