Home >Backend Development >PHP Problem >How to convert an array into a set of variables in php

How to convert an array into a set of variables in php

青灯夜游
青灯夜游Original
2022-05-10 15:17:252394browse

In PHP, list() can be used to convert an array into a set of variables. The syntax is "list(variable 1, variable 2, variable 3....) = $array;". The list() function can assign the values ​​in an array to a set of variables in a single operation. The number of array elements needs to be greater than or equal to the number of parameters in list().

How to convert an array into a set of variables in php

The operating environment of this tutorial: windows7 system, PHP5.5 version, DELL G3 computer

In php, you can use list() to Convert an array into a set of variables.

list() can assign the values ​​​​in an array to a set of variables. Like array(), it is not a real function, but a language structure. list() can assign values ​​to a set of (multiple) variables in a single operation.

Grammar format:

list($var1 [, $val2, ...])=$array;

Parameter description:

  • ##$val1, $val2... is a set of variables to be assigned, and multiple variables are separated by commas , .

  • $array is the array for assignment.


Note: list() can only be used to index arrays, and the index must start from 0. In PHP5, list() starts assigning values ​​from the rightmost parameter; in PHP7, list() starts assigning values ​​from the leftmost parameter.

Example:


<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(1,45,9);
list($a, $b, $c) = $arr;
echo $a."<br>";
echo $b."<br>";
echo $c."<br>";
?>

How to convert an array into a set of variables in php

It can be seen that in the above example, the array is converted into a set of variables ($a, $ b, $c).

Note: The number of array elements can be greater than or equal to the number of parameters in list(), but cannot be less than, otherwise an error will be reported:

<?php
$arr=array(1,45,9,4,5,6);
list($a, $b, $c) = $arr;
echo $a."<br>";
echo $b."<br>";
echo $c."<br>";
?>

How to convert an array into a set of variables in php

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(1,45,9);
list($a, $b, $c, $d) = $arr;
echo $a."<br>";
echo $b."<br>";
echo $c."<br>";
?>

How to convert an array into a set of variables in php

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to convert an array into a set of variables in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn