PHP array() function
In this chapter you will learn:
- Description for PHP array() function
- Syntax for numeric indexed arrays
- Syntax for associative arrays
- Example for array() function
- Example - Creates an associative array named $age
- Example - loop through PHP array
- Example - loop associative array
- Example - multidimensional array
Description
In PHP, there are two types of arrays:
Type | Meaning |
---|---|
Indexed arrays | Arrays with numeric index values |
Associative arrays | Arrays with named keys(key value pair) |
The array() function is used to create an array of above types.
Syntax for numeric indexed arrays
Syntax to use array()
function to create numeric indexed arrays is
as follows.
array(value1,value2,value3,etc.);
Syntax for associative arrays
Syntax to use array() function to create associative arrays is as follows.
array(key=>value,key=>value,key=>value,etc.);
Parameter | Description |
---|---|
key | the key (numeric or string) |
value | the value |
Example 1
Create an indexed array named $names, assign four elements to it, and then print a text containing the array values.
<?php
$names = array("Volvo","BMW","Toyota","PHP from java2s.com");
echo $names[0] . ", " . $names[1] . " and " . $names[3] . ".";
?>
The code above generates the following result.
Example 2
Creates an associative array named $age.
<?php
$age=array("PHP"=>"5","Python"=>"7","Java"=>"4");
echo "PHP is " . $age['PHP'] . " years old.";
?>
The code above generates the following result.
Example 3
Loop through and print all the values of an indexed array
<?php//from ja va 2 s . c om
$cars=array("A","B","C");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++){
echo $cars[$x];
echo "\n";
}
?>
The code above generates the following result.
Example 4
Loop through and print all the values of an associative array.
<?php/* ja va 2 s.com*/
$age=array("PHP"=>"5","Python"=>"7","Java"=>"3");
foreach($age as $x=>$x_value){
echo "Key=" . $x . ", Value=" . $x_value;
echo "\n";
}
?>
The code above generates the following result.
Example 5
Create a multidimensional array.
<?php/*from java 2s . c o m*/
$cars=array(
array("Name"=>"PHP","Price"=>100),
array("Name"=>"Python","Price"=>100),
array("Name"=>"Java","Price"=>10)
);
var_dump($cars);
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Description for PHP array_change_key_case() function
- Syntax for PHP array_change_key_case() function
- Parameter for PHP array_change_key_case() function
- Return value for PHP array_change_key_case() function
- Example for array_change_key_case() function
- Example - If two or more keys will be equal after running array_change_key_case()