In PHP, an array is a data structure that stores a collection of values. Arrays are used to store multiple values in a single variable, and can be used to store data of any type, including strings, integers, booleans, and objects.
There are two types of arrays in PHP: indexed arrays and associative arrays.
Indexed arrays: An indexed array 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.
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.
You can also create an indexed array using the array
function:
$colors = array('red', 'green', 'blue');
// or
$colors = array();
$colors[] = 'red';
$colors[] = 'green';
$colors[] = 'blue';
Associative arrays: An associative array 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.
Here is an example of an associative array in PHP:
$person = array('name' => 'John', 'age' => 30, 'gender' => 'male');
echo $person['name']; // Outputs "John"
echo $person['age']; // Outputs "30"
echo $person['gender']; // Outputs "male"
In this example, the $person
array has three elements with keys ‘name’, ‘age’, and ‘gender’. The elements can be accessed using the array keys in square brackets.
You can also create an associative array using the array
function:
$person = array('name' => 'John', 'age' => 30, 'gender' => 'male');
// or
$person = array();
$person['name'] = 'John';
$person['age'] = 30;
$person['gender'] = 'male';