array
Create a new array
array()
function is used to create an array.
In PHP, there are three types of arrays:
Create an index array named $cars, assign three elements to it, and print the text containing the array value:
<?php $cars = array ( "Volvo" , "BMW" , "Toyota" ) ; echo "I like " . $cars [ 0 ] . ", " . $cars [ 1 ] . " and " . $cars [ 2 ] . "." ; ?>
Try it yourself
Create an associative array named $age:
<?php $age = array ( "Bill" => "60" , "Steve" => "56" , "Mark" => "31" ) ; echo "Bill is " . $age [ 'Bill' ] . " years old." ; ?>
Try it yourself
Iterate over and print the value of the index array:
<?php $cars = array ( "Volvo" , "BMW" , "Toyota" ) ; $arrlength = count ( $cars ) ; for ( $x = 0 ; $x < $arrlength ; $x ++ ) { echo $cars [ $x ] ; echo "<br>" ; } ?>
Try it yourself
Iterate over and print all values of the associative array:
<?php $age = array ( "Bill" => "60" , "Steve" => "56" , "Mark" => "31" ) ; foreach ( $age as $x => $x_value ) { echo "Key=" . $x . ", Value=" . $x_value ; echo "<br>" ; } ?>
Try it yourself
Create a multi-dimensional array:
<?php // Two-dimensional array: $cars = array ( array ( "Volvo" , 100 , 96 ) , array ( "BMW" , 60 , 59 ) , array ( "Toyota" , 110 , 100 ) ) ; ?>
Try it yourself