What is Array?
- An array is a variable that holds multiple values of the same type.
- An array in PHP is an ordered map that associates values to keys.
Syntax
An array can be created by the array() language construct. It takes as parameters any number of comma-separated key => value pairs.
i.e.
$array = array(key1 => value1 , key2 => value2 , ... , keyn => valuen);
(Note: key may be integer or string. If you do not define the key, then PHP parser automatically takes key as Integer and it will starts from 0.)
Types of Array:
In PHP, there are three kind of arrays:
1. Associative or Indexed array: An array where each ID key is associated with a value. Its kind of array whose keys can be numeric or string.
PHP Code: (Example of Associative array)
| <?php //Associative Array $array = array("Fruit" =>"Orange", "Flower" => "Rose", "Vegetable" => "Potato" ); print_r($array); ?> |
Output:
Array
(
[Fruit] => Orange
[Flower] => Rose
[Vegetable] => Potato
)
|
2. Numeric array: An array with a numeric index. Its kind of array whose keys can only be numeric.
PHP Code: (Example of Numeric array)
| <?php //Numeric Array $array = array("Orange","Rose","Potato" ); print_r($array); ?> |
Output:
Array
(
[0] => Orange
[1] => Rose
[2] => Potato
)
|
3. Multidimensional array: An array containing one or more arrays.
PHP Code: (Example of Multidimensional array)
| <?php //Multidimensional Array $array= array ( "Flowers"=>array ( "Rose","Lotus" ), "Fruits"=>array ( "Orange","Pineapple","Banana","Apple" ), "Vegetables"=>array ( "Potato", "Tomato" ) ); print_r($array); ?> |
Output:
Array
(
[Flowers] => Array
(
[0] => Rose
[1] => Lotus
)
[Fruits] => Array
(
[0] => Orange
[1] => Pineapple
[2] => Banana
[3] => Apple
)
[Vegetables] => Array
(
[0] => Potato
[1] => Tomato
)
)
|
What we use in PHP to Display Array:
- print_r displays information about a variable in a way that's readable by humans.We use print_r to display array in PHP.
Regards,
Rohit Modi














