Whenever we want to store related data like list of books, list of students etc at one place, we use an array. An array not only allows to store related data but to organise it as you like and also quickly access to that data. Array can be effectively manipulated. In PHP, arrays are indexed from 0 and not from 1.
PHP has three types of arrays
Array can be specified in following two different ways
Syntax
$arrayName=array(var1,var2,....);
<?php $myChice=array("Red","Science","Sunday"); echo "My favorite colour is".$myChoice[0].", my fav subject is".$myChioce[1]."and my fav day is".$myChoice[2]; ?>
This will produce following result
My favorite colour is Red, my fav subject is Science and my fav day is Sunday
Syntax:
$arrayName['key']=value;
<?php $myChice[0]="Red"; $myChoice[1]="Science"; $myChoice[2]="Sunday"; echo "My favorite colour is".$myChoice[0].", my fav subject is".$myChioce[1]."and my fav day is".$myChoice[2]; ?>
This will produce following result
My favorite colour is Red, my fav subject is Science and my fav day is Sunday
This can be done using implode() function.
<?php $myChice=array("Red","Science","Sunday"); echo implode(" ",$myChoice); ?>
This will produce following result
Red Science Sunday
This can also be done using implode() function but differntly.
<?php $myChice=array("Red","Science","Sunday"); echo substr(implode(',',$myChoice),0,-2); ?>
This will produce following result
Red,Science,Sunday
This can be done using array_reverse() function.
<?php $myChice=array("Red","Science","Sunday"); echo "Original array:".substr(implode(',',$myChoice),0,-2); echo "</br>"; $myChoice=array_reverse($myChoice); echo "Reversed array:".substr(implode(',',$myChoice),0,-2); ?>
This will produce following result
Original array: Red,Science,Sunday Reversed array:Sunday,Science,Red
This can be done using array_slice() function.
<?php $myChice=array("Red","Science","Sunday","Brown","Arts","Tuesday"); $colChoice=array_slice($myChoice,0,3); echo "My Colour Choice array:".substr(implode(',',$colChoice),0,-2); ?>
This will produce following result
My Colour Choice array: Red,Brown
This can be done using array_splice() function.
<?php $myChice=array("Red","Science","Sunday"); echo "Original array:".substr(implode(',',$myChoice),0,-2); echo "</br>"; $trmyChoice=array_splice($myChoice,2); echo "Trimmed array:".substr(implode(',',$trmyChoice),0,-2); ?>
This will produce following result
Original array: Red,Science,Sunday Trimmed array:Red,Science
This can be done using count() function.
<?php $myChice=array("Red","Science","Sunday","Brown","Arts","Tuesday"); echo count($myChoice); ?>
This will produce following result
6