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/*www.j a va2 s.  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/* w ww.j a  va 2s  .  com*/
$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/*w  ww .j  av a2s. 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/*  w  ww  .  j  a  v  a2 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//w  w w .j a v  a  2s  . 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.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions