← Back to Chapters

PHP Array list() Function

? PHP Array list() Function

? Quick Overview

The list() function in PHP allows you to assign values from an indexed array directly into individual variables in a single operation. It improves readability and is commonly used when unpacking array data.

⚡ Interactive list() Simulator

Modify the array elements below to see how list($a, $b, $c) maps them to variables.

$var1 Apple
$var2 Banana
$var3 Cherry

? Key Concepts

  • list() works only with numerically indexed arrays.
  • Values are assigned based on array index order.
  • Frequently used with foreach for multi-dimensional arrays.

? Syntax & Theory

The list() construct assigns array elements to variables in the order they appear.

? View Code Example
// Basic syntax of list() with an indexed array
list($var1, $var2, $var3) = $array;

? Example 1: Using list() with an Indexed Array

This example shows how array values are unpacked into separate variables.

? View Code Example
// Assign array elements to individual variables
<?php
$array = array("apple", "banana", "cherry");
list($fruit1, $fruit2, $fruit3) = $array;
echo $fruit1;
echo $fruit2;
echo $fruit3;
?>

? Live Output / Explanation

The output will display each fruit in sequence. Each variable receives the value from the corresponding array index.

? Example 2: Using list() with a Multi-dimensional Array

When working with structured data, list() is often combined with foreach.

? View Code Example
// Unpacking sub-array values inside a foreach loop
<?php
$fruits = array(
    array("apple", 1),
    array("banana", 2),
    array("cherry", 3)
);
foreach ($fruits as list($name, $quantity)) {
    echo "$name: $quantity<br>";
}
?>

? Interactive Visualization

The diagram below illustrates how array indexes map to variables when using list().

Index 0 → $fruit1 Index 1 → $fruit2 Index 2 → $fruit3

? Use Cases

  • Extracting database query results.
  • Processing CSV or API response arrays.
  • Cleaner iteration over structured datasets.

✅ Tips & Best Practices

  • Always ensure array indexes match variable order.
  • Use list() for readability when unpacking arrays.
  • Avoid using it with associative arrays.

? Try It Yourself

  • Unpack an array of numbers into variables and print their sum.
  • Use list() inside a foreach loop to display student names and grades.
  • Create a price list array and unpack values dynamically.