PHP list

Summary: in this tutorial, you’ll learn how to use the PHP list syntax to assign multiple variables in one operation.

Introduction to the PHP list syntax #

Suppose you have an array that contains two numbers:

<?php

$prices  = [100, 0.1];Code language: PHP (php)

To assign each element of the $prices array to variables, you’ll do it like this:

<?php

$pices = [100, 0.1];
$buy_price = $prices[0];
$tax = $price[1];Code language: PHP (php)

The code assigns the first element and second element of the array $prices to $buy_price and $tax variables respectively. But you need two assignments to assign two 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 assignment:

list(var1, var2, ...) = $array;Code language: PHP (php)

For example:

<?php

$prices  = [100, 0.1];
list($buy_price, $tax) = $prices;

var_dump( $buy_price, $tax );Code language: PHP (php)

Try it

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 a 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:

<?php

$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)

Try it

Output:

The price is 100 with the discount of 0.05Code language: JavaScript (javascript)

2) Using the nested list to assign variables #

The following example uses the nested list to assign the array’s elements to the variables:

<?php

$elements = ['body', ['white','blue']];
list($element, list($bgcolor, $color)) = $elements;

var_dump($element, $bgcolor, $color);Code language: PHP (php)

Try it

Output:

string(4) "body" 
string(5) "white"
string(4) "blue" Code language: JavaScript (javascript)

3) Using a 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:

<?php

$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)

Try it

Output:

string(4) "John" 
string(3) "Doe" 
int(25)Code language: JavaScript (javascript)

Summary #

  • Use PHP list() construct to assign multiple variables in one operation.
Did you find this tutorial useful?