In PHP, arrays are versatile and widely used data structures that allow you to store multiple values in a single variable. PHP supports several types of arrays, including indexed arrays, associative arrays, and multidimensional arrays. Here's an overview of each type:
Indexed arrays store a collection of values where each value is identified by a numeric index, starting from 0.
Creating Indexed Arrays:
$colors = array("Red", "Green", "Blue");
Accessing Indexed Array Elements:
echo $colors[0]; // Output: Red
echo $colors[1]; // Output: Green
echo $colors[2]; // Output: Blue
Associative arrays store key-value pairs where each key is associated with a specific value.
Creating Associative Arrays:
$person = array("name" => "John", "age" => 30, "city" => "New York");
Accessing Associative Array Elements:
echo $person["name"]; // Output: John
echo $person["age"]; // Output: 30
echo $person["city"]; // Output: New York
Multidimensional arrays are arrays within arrays, allowing you to create a hierarchical structure.
Creating Multidimensional Arrays:
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
Accessing Multidimensional Array Elements:
echo $matrix[0][0]; // Output: 1
echo $matrix[1][2]; // Output: 6
echo $matrix[2][1]; // Output: 8
PHP provides many built-in functions for working with arrays, such as count, array_push, array_pop, array_shift, array_unshift, sort, rsort, array_keys, array_values, etc.
Example:
$numbers = array(3, 1, 4, 1, 5, 9, 2);
echo count($numbers); // Output: 7
sort($numbers);
print_r($numbers); // Output: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 9 )
These are the basics of working with arrays in PHP. Arrays are fundamental data structures in PHP programming and are extensively used in various applications.