PHP list() Function

What is PHP list() Function?

If you want to assign values of an array to a list of variables in a single statement, use PHP list() function.

Syntax:

list(variable1, variable2, variable3,… variableN);

Parameters:

The Function has 1 required parameter and one or more optional parameter-

Variable1 (Required): It is the first variable.

variable2, variable3,… variableN (Optional): These are one or more variables.

Return Values:

The function returns the original array. Check example 2.

Examples:

Example 1:

<?php
$language = ["HTML", "CSS", "JavaScript" , "PHP"];
list($a, $b, $c, $d) = $language; 
echo "Markup language: " .$a . "<br>";
echo "Style sheet language: " .$b . "<br>";
echo "Scripting language: " .$c . "<br>";
?>

Output:

Markup language: HTML
Style sheet language: CSS
Scripting language: JavaScript

Explanation:

CODE GOES HERE………

Example 2:

<pre>
<?php
$language = ["HTML", "CSS", "JavaScript" , "PHP"];
$returned_value = list($a, $b, $c, $d) = $language; 
print_r($returned_value);
?>
</pre>

Output:

Array
(
[0] => HTML
[1] => CSS
[2] => JavaScript
[3] => PHP
)

Example 3:

<?php
$language1 = ["HTML", "CSS", "JavaScript"];
list($a, $b, $c, $d) = $language1;
echo "Markup language: " .$a . "<br>";
echo "Style sheet language: " .$b . "<br>";
echo "Scripting language: " .$c . "<br>";
echo "Server side language: " .$d . "<br>";
?>

Output:

Warning: Undefined array key 3 in D:\xampp\htdocs\list.php on line 3
Markup language: HTML
Style sheet language: CSS
Scripting language: JavaScript
Server side language:

Example 4:

<?php
$language = ["HTML", "CSS", "JavaScript" , "PHP"];
list($a, , , $b) = $language; 
echo "Markup language: " .$a . "<br>";
echo "Server side language: " .$b . "<br>";
?>

Output:

Markup language: HTML
Server side language: PHP

Example 5:

<?php
$frontend = ["Markup" => "HTML", "Styling" => "CSS", "Scripting" => "JavaScript"];
list("Markup" => $MU, "Styling" => $STL, "Scripting" => $SCT) = $frontend; 
echo "Markup language: " . $MU . "<br>";
echo "Style sheet language: " . $STL . "<br>";
echo "Scripting language: " . $SCT;
?>

Output:

Markup language: HTML
Style sheet language: CSS
Scripting language: JavaScript

Notes on list() Function:

  • list() is actually a language construct not a function.
  • List() is also called “array destructuring” as it extracts elements from an array to individual variables in a single statement.
  • You can skip an element by just omitting it but keeping its comma. Check example 4.

Caution:

If you try to access assign more variables than the number of item exists in the array, PHP throws an E_WARNING. Check example 2.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP list() Function

The list() function is a built-in PHP function and part of the PHP’s array functions. PHP list() construct is a quick and easy way to extract array elements to variables.

Reference:

https://www.php.net/manual/en/function.list.php