PHP list
Introduction to the PHP list syntax
Suppose you have an array that contains two numbers:
$prices = [100, 0.1];
Code language: PHP (php)
To assign each element of the $prices
array to variables, you’ll do it like this:
$pices = [100, 0.1];
$buy_price = $prices[0];
$tax = $price[1];
Code language: PHP (php)
The code is straightforward. It assigns the first element of the array to the $buy_price
and the second element to the $tax
variable.
However, you need two operations to assign two array elements to two variables.
PHP provides the list()
construct that assigns the elements of an array to a list of variables in one operation:
list(var1, var2, ...) = $array;
Code language: PHP (php)
For example:
$prices = [100, 0.1];
list($buy_price, $tax) = $prices;
var_dump( $buy_price, $tax );
Code language: PHP (php)
Output:
int(100)
float(0.1)
Code language: CSS (css)
In this example, the list assigns the first element of the $prices array to the $buy_price variable and the second element of the $price
array to the $tax
variable.
Note that like array()
, list()
is not a function but a language construct.
PHP list examples
Let’s take some examples of using the list construct.
1) Using list to skip array elements
The following example uses the list to assign the first and the third element to variables. It skips the second element:
$prices = [100, 0.1, 0.05];
list($buy_price, , $discount) = $prices;
echo "The price is $buy_price with the discount of $discount";
Code language: PHP (php)
Output:
The price is 100 with the discount of 0.05
Code language: JavaScript (javascript)
2) Using the nested list to assign variables
The following example uses the nested list to assign array’s elements to the variables:
$elements = ['body', ['white','blue']];
list($element, list($bgcolor, $color)) = $elements;
var_dump($element, $bgcolor, $color);
Code language: PHP (php)
Output:
string(4) "body"
string(5) "white"
string(4) "blue"
Code language: JavaScript (javascript)
3) Using PHP list with an associative array
Starting from PHP 7.1.0, you can use the list construct to assign elements of an associative array to variables. For example:
$person = [
'first_name' => 'John',
'last_name' => 'Doe',
'age' => 25
];
list(
'first_name' => $first_name,
'last_name' => $last_name,
'age' => $age) = $person;
var_dump($first_name, $last_name, $age);
Code language: PHP (php)
Output:
$person = [
'first_name' => 'John',
'last_name' => 'Doe',
'age' => 25
];
list(
'first_name' => $first_name,
'last_name' => $last_name,
'age' => $age) = $person;
var_dump($first_name, $last_name, $age);
Code language: HTML, XML (xml)
Summary
- Use PHP
list()
construct to assign multiple variables in one operation.