Home > Backend Development > PHP Problem > What is the function of list in php

What is the function of list in php

爱喝马黛茶的安东尼
Release: 2023-02-23 12:46:01
Original
3327 people have browsed it

What is the function of list in php

list() is used to assign values ​​to a set of variables in one operation.

Note: list() is only used for numerically indexed arrays, and it is assumed that numerical indexing starts from 0.

Description

list() assigns a value to a set of variables using elements in the array.

Note that, similar to array(), list() is actually a language structure, not a function.

Related recommendations: "PHP Getting Started Tutorial"

For example:

<?php
  $my_array = array(&#39;Dog&#39;,&#39;Cat&#39;,&#39;Horse&#39;);
  list($a, $b, $c) = $my_array;
  echo &#39;I have several animals, a &#39;.$a.&#39;, a &#39;.$b.&#39; and a &#39;.$c;
?>
Copy after login

The result is as follows, which can be output normally

What is the function of list in php

When the array is not a numeric array but an associative array, such as:

<?php
$my_array = array(&#39;a&#39;=>&#39;Dog&#39;,&#39;b&#39;=>&#39;Cat&#39;,&#39;c&#39;=>&#39;Horse&#39;);
list($a, $b, $c) = $my_array;
echo &#39;I have several animals, a &#39;.$a.&#39;, a &#39;.$b.&#39; and a &#39;.$c;
?>
Copy after login

The result will be an error

What is the function of list in php

When using the index array is For example:

<?php
  $my_array = array(0=>&#39;Dog&#39;,1=>&#39;Cat&#39;,2=>&#39;Horse&#39;);
  list($a, $b, $c) = $my_array;
  echo &#39;I have several animals, a &#39;.$a.&#39;, a &#39;.$b.&#39; and a &#39;.$c;
?>
Copy after login

This can be output normally. When the code is changed to:

<?php
$my_array = array(1=>&#39;Dog&#39;,2=>&#39;Cat&#39;,3=>&#39;Horse&#39;);
list($a, $b, $c) = $my_array;
echo &#39;I have several animals, a &#39;.$a.&#39;, a &#39;.$b.&#39; and a &#39;.$c;
?>
Copy after login

, the output result is as follows:

What is the function of list in php

The variable $a is merged It is not assigned, and the element with subscript 1 is assigned to the second variable $b. That is to say, the first element in list() is assigned with subscript 0, and the second element is assigned with subscript 1. Assignment, the third element is assigned with index 2, and so on.

The above is the detailed content of What is the function of list in php. 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