PHP Arrays
Arrays are complex variables that allow us to store more than one v alue or a group of values under a single variable name.
An array is created using an array() function in PHP.
Types of Arrays in PHP
There are three types of arrays that you can create. These are:
Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly.
Associative Arrays: An array with a string index where instead of linear storage, each value can be assigned a specific key.
Multidimensional Arrays: An array which contains single or multiple array within it and can be accessed via multiple indices.
PHP Indexed Array
PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default.
Defining indexed array
There are two ways to define indexed array:
// One way to create an indexed array $colors = array("red", "gree", "yellow", "white", "black"); // Second way to create an indexed array // This way assigns the index manually $cars[0] = "BMW"; $cars[1] = "TATA"; $cars[2] = "TOYOTA"; $cars[3] = "HONDA"; $cars[4] = "AUDI";
Accessing the elements
There are two ways to accessing the elements:
// Accessing the elements directly by their index. echo "Accessing the colors array elements directly:\n"; echo $colors[2], "\n"; echo $colors[0], "\n"; echo $colors[4], "\n"; // Second way to create an accessing the elements // Looping through a numeric array using a for loop foreach( $colors as $value ) { echo "Color is $value <br>"; }
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.
Keys are descriptive captions of the array element used to access the value of the array. And value is the value assigned to the array element.
Defining indexed array
// One way to create an associative array $score = array("Gopal"=>"95.5", "Raghav"=>"96.0", "Ram"=>"97.0", "Kiran"=>"93.0", "Ravi"=>"95.0"); // Second way to create an associative array $score["Gopal"] = "95.5"; $score["Raghav"] = "96.0"; $score["Ram"] = "97.0"; $score["Kiran"] = "93.0"; $score["Ravi"] = "95.0";
Accessing the elements
// Accessing the elements directly echo "Accessing the elements directly:\n"; echo $score["Gopal"], "\n"; echo $score["Raghav"], "\n"; echo $score["Ram"], "\n"; echo $score["Kiran"], "\n"; echo $score["Ravi"], "\n"; // Looping through an array using foreach echo "Looping using foreach: \n"; foreach ($score as $val => $val_value){ echo "Score of ".$val." is ".$val_value."\n"; } // Looping through an array using for echo "\nLooping using for: \n"; $keys = array_keys($score); $round = count($score); for($i=0; $i < $round; ++$i) { echo $keys[$i] . ' ' . $score[$keys[$i]] . "\n"; }