PHP, an array is a data structure that can hold multiple values under a single variable name. An array can store different data types such as integers, floats, strings, and even other arrays.
There are two types of arrays in PHP: indexed arrays and associative arrays.
Indexed Arrays: Indexed arrays are the most common type of arrays in PHP. They are used to store a collection of values, which are assigned a numerical index starting from zero.
Here’s an example of creating an indexed array in PHP:
$fruits = array("apple", "banana", "orange", "grape");
In this example, we have created an indexed array named $fruits
that contains four elements. Each element is assigned an index from 0 to 3.
To access a specific element of the array, we can use the index value like this:
echo $fruits[1]; // Output: banana
Associative Arrays: Associative arrays, on the other hand, use key-value pairs to store data. The key is a unique identifier for each value stored in the array.
Here’s an example of creating an associative array in PHP:
$person = array("name" => "John", "age" => 30, "city" => "New York");
In this example, we have created an associative array named $person
that contains three key-value pairs. The keys are “name”, “age”, and “city”, and the values are “John”, 30, and “New York”, respectively.
To access a specific value of the array, we can use the key like this:
echo $person["name"]; // Output: John