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

autoload
Release: 2023-04-09 22:06:01
Original
5794 people have browsed it

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
Copy after login
  • $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";
?>
Copy after login
输出:coffee is brown and caffeine makes it special
Copy after login

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.";
Copy after login
输出:coffee has caffeine.
Copy after login

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!";
Copy after login
输出:I need caffeine!
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template