An array in PHP is a special variable that can hold more than one value at a time. It is a data structure that stores one or more similar types of values in a single value. Arrays can be used to store a list of items, such as a list of car names, and can hold many values under a single name. There are three types of arrays in PHP:
- Indexed arrays: These are arrays with a numeric index. Values are stored and accessed in a linear fashion.
- Associative arrays: These are arrays with named keys. This stores element values in association with key values rather than in a strict linear index order.
- Multidimensional arrays: These are arrays containing one or more arrays, and values are accessed using multiple indices.
To create an array in PHP, the array()
function is used. By default, an array of any variable starts with the 0 index. An array can hold many values under a single name, and you can access the values by referring to an index number. The count()
function is used to return the length (the number of elements) of an array.
Here is an example of creating an indexed array in PHP:
$numbers = array(8, 20, 40, 58, 88, 200, 400, 500);
And here is an example of creating an associative array in PHP:
$name_one = array("Zack"=>"Zara", "Anthony"=>"Any", "Ram"=>"Rani", "Salim"=>"Sara", "Raghav"=>"Ravina");
And here is an example of creating a multidimensional array in PHP:
$staff = array(
array("name"=>"John", "email"=>"[email protected]", "reg_no"=>"1234"),
array("name"=>"Jane", "email"=>"[email protected]", "reg_no"=>"5678"),
array("name"=>"Bob", "email"=>"[email protected]", "reg_no"=>"9012")
);
Arrays are an essential part of PHP programming and are used extensively in web development.