PHP Array is usedto hold more than one value at a time. In another words, we can say that an array stores multiple values in one single variable.
Following are the advantages of Array.
- It reduces the code.
- We can store data easily.
- Easy to traverse.
How to create Array in PHP
In PHP, the array() function is used to create an array.
Syntax:
1 2 3 |
array(); |
Example
1 2 3 4 5 6 |
<?php $arr = array(10,11,12,13,14,15); echo $arr[0]; ?> |
Output
10
There are three types of array in PHP:
- Indexed Array
- Associative Array
- Multidimensional Array
PHP Indexed Arrays
PHP indexed array is used to store the number, string and object. Itis represented by number andstarts with 0.
There are two ways to represent indexed array:
1stway:
1 2 3 |
$name=array("Rohit","Rohan","Shyam"); |
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <html> <head> <title>PHP Tutorial</title> </head> <body> <?php $name=array("Geeta","Rohan","Shyam"); echo "Your Name: $name[0],$name[1],$name[2]"; ?> </body> </html> |
Output
Your Name: Geeta,Rohan,Shyam
2nd Ways:
1 2 3 4 5 |
$name[0]="Geeta"; $name[1]="Rohit"; $name[2]="Shyam"; |
Example2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html> <head> <title>PHP Tutorial</title> </head> <body> <?php $name[0]="Geeta"; $name[1]="Rohit"; $name[2]="Shyam"; echo "Your Name: $name[0],$name[1],$name[2]"; ?> </body> </html> |
Output
Your Name: Geeta,Rohit,Shyam
Exqmple3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<html> <head> <title>PHP Tutorial</title> </head> <body> <?php $size=array("Geeta","Rohit","Shyam"); //Traversing PHP Indexed Array foreach($size as $s){ echo "Your Name:$s<br />"; } ?> </body> </html> |
Output
Hello John
Hello Ram
Hello Rohan
Example4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <html> <head> <title>PHP Tutorial</title> </head> <body> <?php $size=array("Geeta","Rohit","Shyam"); echo count($size); ?> </body> </html> |
Output
3