Array in PHP
In PHP, an array is a data structure that allows you to store multiple values in a single variable. Each value in an array is identified by a unique key or index. The key can be either numeric or a string, depending on the type of array.
PHP Supports Three Main Types of Arrays:
Indexed Arrays: In an indexed array, elements are stored with numeric indices. The first element has an index of 0, the second element has an index of 1, and so on.
$numericArray = array("Apple", "Banana", "Orange");
echo $numericArray[0]; // Outputs: Apple
Associative Arrays: In an associative array, elements are stored with named keys. Each element has a key-value pair, where the key is a string.
$assocArray = array("name" => "John", "age" => 30, "city" => "New York");
echo $assocArray["name"]; // Outputs: John
Multidimensional Arrays: A multidimensional array is an array that contains one or more arrays. It can be a combination of indexed and associative arrays.
$multiArray = array(
array("Apple", "Banana", "Orange"),
array("name" => "John", "age" => 30),
array(1, 2, 3)
);
echo $multiArray[0][0]; // Outputs: Apple
echo $multiArray[1]["name"]; // Outputs: John
Arrays in PHP are dynamic, meaning you can easily add, modify, or remove elements during runtime. PHP provides a wide range of built-in functions for working with arrays, such as count()
, array_push()
, array_pop()
, array_merge()
, and many more.
Here's an example of adding an element to an array:
$fruits = array("Apple", "Banana", "Orange");
$fruits[] = "Grapes"; // Adds "Grapes" to the end of the array
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Grapes )
Arrays are fundamental in PHP and are widely used for storing and manipulating data in various web applications.
Thank you.