An array is used to store multiple values in a single value. In PHP, it orders maps of pairs of keys and values. It saves the collection of the data type.
In PHP, an array is a data structure that can store multiple values under a single variable name. It can hold different types of data such as integers, strings, objects, or even other arrays. Arrays in PHP can be indexed numerically (starting from zero) or associatively (using string keys). Here’s a breakdown:
- Numerically Indexed Array: This type of array assigns numeric keys to each element, starting from zero.
php
$numericalArray = array("apple", "banana", "orange");
// Or, starting from PHP 5.4, you can use the shorthand syntax:
// $numericalArray = ["apple", "banana", "orange"];echo $numericalArray[0]; // Outputs: apple
echo $numericalArray[1]; // Outputs: banana
echo $numericalArray[2]; // Outputs: orange
- Associative Array: In an associative array, each element is associated with a specific key.
php
$associativeArray = array("name" => "John", "age" => 30, "city" => "New York");
echo $associativeArray["name"]; // Outputs: John
echo $associativeArray["age"]; // Outputs: 30
echo $associativeArray["city"]; // Outputs: New York
- Multidimensional Array: Arrays can also contain other arrays, creating multidimensional arrays.
php
$multidimensionalArray = array(
array("apple", "banana", "orange"),
array("carrot", "lettuce", "tomato")
);echo $multidimensionalArray[0][0]; // Outputs: apple
echo $multidimensionalArray[1][2]; // Outputs: tomato
Arrays are widely used in PHP for storing and manipulating data efficiently. They provide flexibility and ease of use in handling collections of values.