PHP Tutorial - PHP list() Function






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

ParameterIs RequiredDescription
var1Required.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
$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
$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
         $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
         $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
    $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.