Current Location: Home> Function Categories> array

array

Create a new array
Name:array
Category:Array
Programming Language:php
One-line Description:Create an array.

Definition and usage

array() function is used to create an array.

In PHP, there are three types of arrays:

  • Index array - an array with numeric index
  • Associative array - an array with specified keys
  • Multidimensional array - an array containing one or more arrays

Example

Example 1

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

Example 2

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

Example 3

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

Example 4

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

Example 5

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

Similar Functions
Popular Articles