An array is a single variable which can store multiple values at a time. Thus, PHP array is used to hold many values under a single name. These values can be accessed the by referring to their index number.
$arrayName = array(value 1, value 2, ...);
Types of Array:
PHP supports three types of array. These are:
- Indexed arrays
- Associative arrays
- Multidimensional arrays
Advantages of using Array in PHP:
- Single variable need to be declared, instead of multiple variable, making the code user friendly.
- Less number of lines needed in a code.
- Traversing of all the elements is easy.
- Functions like sorting can be easily applied to all the elements.
Example 1: Using elements of an array.
<!DOCTYPE html> <html> <body> <?php $food = array("PIZZA", "BURGER", "COKE"); echo "I love to eat " . $food . ", " . $food . " and " . $food . "."; ?> </body> </html>
I love to eat PIZZA, BURGER and COKE.
Example 2: Counting the number of elements in an array.
<!DOCTYPE html> <html> <body> <?php $food = array("PIZZA", "BURGER", "COKE"); echo count($food); ?> </body> </html>