Home >Backend Development >PHP Tutorial >In-depth analysis of lists in PHP (with code examples)

In-depth analysis of lists in PHP (with code examples)

autoload
autoloadOriginal
2021-04-25 10:30:465830browse

PHPThere are several ways to assign the value of an array to a set of variables. It is more convenient to use the extract() function, but for index array Language is more troublesome, so we can use list to solve this problem. This article will take you to take a look.

First, let’s take a look at the syntax of list():

list    ( mixed $var   , mixed ...$vars = ?   ) = $arr
  • $arr: Specify array

  • $var: a variable.

  • #$vars: More variables.

  • Return value: Return the specified array.

Code example:

1. List all variables in the array:

<?php
$info = array(&#39;coffee&#39;, &#39;brown&#39;, &#39;caffeine&#39;);
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special";
?>
输出:coffee is brown and caffeine makes it special

2. Omit one variable in the array:

<?php
$info = array(&#39;coffee&#39;, &#39;brown&#39;, &#39;caffeine&#39;);
list($drink, , $power) = $info;
echo "$drink has $power.";
输出:coffee has caffeine.

3. Only the third variable in the array

<?php
$info = array(&#39;coffee&#39;, &#39;brown&#39;, &#39;caffeine&#39;);
list( , , $power) = $info;
echo "I need $power!";
输出:I need caffeine!

4.list() cannot work on strings

<?php
$info = array(&#39;coffee&#39;, &#39;brown&#39;, &#39;caffeine&#39;);
list($bar) = "abcde";
var_dump($bar); // NULL

Recommendation:2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of In-depth analysis of lists in PHP (with code examples). 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