Using PHP list() to Assign Array Values to Variables

This article explains how PHP's list() function can assign values from an indexed array to multiple variables, compares it with extract(), and provides four code examples illustrating full assignment, skipping elements, selecting a single element, and the limitation with strings.

php Courses
php Courses
php Courses
Using PHP list() to Assign Array Values to Variables

In PHP, assigning values from an indexed array to several variables can be done with the extract() function, but list() offers a more convenient syntax for indexed arrays. This article introduces the list() construct and shows how to use it.

The syntax of list() is: list ( mixed $var , mixed ...$vars = ? ) = $arr where $arr is the source array, $var represents a single variable, $vars represents additional variables, and the expression returns the specified array.

1. List all array variables:

<?php
$info = array('coffee', 'brown', 'caffeine');
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special";
?>

Output: coffee is brown and caffeine makes it special 2. Omit one variable:

<?php
$info = array('coffee', 'brown', 'caffeine');
list($drink, , $power) = $info;
echo "$drink has $power.";
?>

Output: coffee has caffeine. 3. Use only the third variable:

<?php
$info = array('coffee', 'brown', 'caffeine');
list( , , $power) = $info;
echo "I need $power!";
?>

Output: I need caffeine! 4. list() cannot operate on strings:

<?php
$info = array('coffee', 'brown', 'caffeine');
list($bar) = "abcde";
var_dump($bar); // NULL
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPListVariables
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.