How to extract arrays with list() in php ?

The list() function is used to assign the values to the list of variables in single operation.

Note: 
The list() function works only on numerical arrays.

Syntax :

list(var1,var2…)

Example for list function :

<?php

$lists = array(‘Bike’, ‘car’, ‘bus’ , ‘truck’);

list($a[0], $a[1], $a[2]) = $lists;

var_dump($a);

?>

Output :

array(3) { [0]=> string(4) “Bike” [1]=> string(3) “car” [2]=> string(3) “bus” }

Lets take a another example :

<?php

$lists = array(‘PHP’, ‘Intresting’, ‘learn’  );

// Listing all the variables
list($p1, $p2, $p3) = $lists;


echo “$p1 is $p2 language to  $p3 .”;

echo “<br/>”;

// Listing some of them
list($p1 , $p2 , ) = $lists;

echo “$p1 is $p2.”;

echo “<br/>”;

// Or let’s skip to only the third one
list( , , $p3) = $lists;
echo “I need to $p3 !”;

echo “<br/>”;

?>

Output : 
PHP is Intresting language to learn .
PHP is Intresting.
I need to learn !

Leave a Reply

Your email address will not be published.Required fields are marked *