Hướng dẫn
Quảng cáo

Hàm list() trong PHP

Hướng dẫn cách sử dụng hàm list() về mảng trong lập trình PHP

Tác dụng của hàm list()

The list() function assign variables as if they were an array.

Like array(), this is not really a function, but a language construct. This function is mainly used to assign a list of variables in one operation. It doesn't work with strings.

The following table summarizes the technical details of this function.

Return Value: Returns the assigned array.
Changelog: Since PHP 7.1.0, it is now possible to specify keys in the list(). Previously, it only worked on numerical arrays and assumes the numerical indices start at 0.
Version: PHP 4+


The basic syntax of the list() function is given with:

list(variable1, variable2, ...);

The following example shows the list() function in action.

// Sample array
$phone = array("Apple", "iPhone", "128GB");

// Listing all the variables
list($brand, $model, $rom) = $phone;
echo "This is an $brand $model with $rom internal storage.";


The list() function accepts the following parameters.

Parameter Description
variable1 Required. Specify a variable to assign a value to.
variable2, ... Optional. Specify more variables to assign values to.

More Examples

Here're some more examples showing how list() function actually works:

The following example demonstrates how to skip the listing of some of the variables. However, since PHP 7.0.0, the list() expressions can no longer be completely empty.

// Sample array
$phone = array("Apple", "iPhone", "128GB");

// Listing some of them
list($brand, , $rom) = $phone;
echo "This is an $brand device with $rom internal storage.";

// Listing the third one
list(, , $rom) = $phone;
echo "This is a mobile device with $rom internal storage.";

Bài viết này đã giúp ích cho bạn?

Bài viết mới