PHP list() Function
In this chapter you will learn:
- Definition for PHP list() Function
- Syntax for PHP list() Function
- Parameter for PHP list() Function
- Note for PHP list() Function
- Example - Assign value in an array to a list of variables
- Example - Using the first and third variables
- Example - Compare the code with and without list() function
- Example - Use list during array loop
Definition
The list() function is used to assign values to a list of variables in one operation.
Syntax
PHP list() Function has the following syntax.
list(var1,var2...)
Parameter
Parameter | Is Required | Description |
---|---|---|
var1 | Required. | The first variable to assign a value to |
var2,... | Optional. | More variables to assign values to |
Note
This function only works on numerical arrays.
Example 1
Assign value in an array to a list of variables
<?php/*from j a va2s . c o m*/
$my_array = array("A","B","C");
list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
?>
The code above generates the following result.
Example 2
Using the first and third variables:
<?php/* j ava 2 s. c o m*/
$my_array = array("A","B","C");
list($a, , $c) = $my_array;
echo "Here I only use the $a and $c variables.";
?>
The code above generates the following result.
Example 3
list() pulls out the values of an array into separate variables.
<?PHP/* j a va 2s.c o m*/
$myBook = array( "Learn PHP from java2s.com", "java2s.com", 2000 );
$title = $myBook[0];
$author = $myBook[1];
$pubYear = $myBook[2];
echo $title . "\n";
echo $author . "\n";
echo $pubYear . "\n";
?>
You use it as follows:
<?PHP/*from ja va 2 s . c o m*/
$myBook = array( "Learn PHP from java2s.com", "java2s.com", 2000 );
list( $title, $author, $pubYear ) = $myBook;
echo $title . "\n";
echo $author . "\n";
echo $pubYear . "\n";
?>
list() only works with indexed arrays, and it assumes the elements are indexed consecutively starting from zero so the first element has an index of 0 , the second has an index of 1 , and so on.
Example 4
A classic use of list() is with functions such as each() that return an indexed array of values. For example:
<?PHP//from jav a2 s . c o m
$myBook = array( "title" => "Learn PHP from java2s.com",
"author" => "java2s.com",
"pubYear" => 2000 );
while ( list( $key, $value ) = each( $myBook ) ) {
echo "Key: $key \n";
echo "Value: $value";
}
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP natcasesort() Function
- Syntax for PHP natcasesort() Function
- Parameter for PHP natcasesort() Function
- Return for PHP natcasesort() Function
- Note for PHP natcasesort() Function
- Example - sorts an array by using a "natural order" algorithm