Arrays in PHP
In other programming languages arrays are used to store multiple values of same type but PHP has one more advantage since it’s not a type language so arrays can save values of different data types at same place.
Declaration of array in PHP:
In PHP array() function is used to create an array:
1 2 3 |
<?php $arr = array(1,2,3,4); ?> |
Types of Arrays:
There are two types of arrays in PHP
- Numeric arrays
- Associative arrays
Numeric Arrays or Indexed Arrays:
As the name, these arrays are same as we have in other programming languages they have simple numeric indexing starts from zero. We don’t define the index of arrays.
1 2 3 4 5 6 7 8 |
<?php $arr = array (307,315,321,345); echo $arr[0]; echo $arr[1]; echo $arr[2]; echo $arr[3]; ?> |

Loop on numeric arrays:
To loop numeric or indexed array we have to use simple for or foreach loop.
1 2 3 4 5 6 7 |
<?php $arr = array (307,315,321,345); foreach($arr as $value){ echo $value."<br>"; } ?> |
Find Length of array in PHP:
To find the length of array in PHP count () function is used. This function returns the length of the array which we pass in it as argument.
1 2 3 4 5 6 7 8 9 10 |
<?php $arr = array ("ali","usman","ahmed","bilal"); $length = count($arr); for($x = 0;$x<$length;$x++){ echo $arr[$x]."<br>"; } ?> |
Associative arrays in PHP:
This type of array uses key to assign value on index. Instead of auto numeric indexing you should define every index.
1 2 3 4 5 6 7 |
<?php $array = array("p1"=>"Ali","p2"=>"usman","p3"=>"Hairs"); echo "Person one has named: ".$array['p1']; echo "Person two has named: ".$array['p2']; echo "Person three has named: ".$array['p3']; ?> |

Loop on associative array:
1 2 3 4 5 6 7 |
<?php $array = array("p1"=>"Ali","p2"=>"usman","p3"=>"Hairs"); foreach($array as $person=>$person_name){ echo "Index:".$person." Value: ". $person_name."<br>"; } ?> |
Multidimensional Array:
In PHP same like JavaScript multidimensional or 2D array is array with in another array.
1 2 3 4 5 6 7 8 9 |
<?php $array = array (array (11, 12, 13), array (21, 22, 23)); foreach($array as $x){ foreach($x as $y){ echo $y; } } ?> |