PHP 将数组分配给变量

2022-08-30 13:01:31

我不确定我的记忆是否错误,但是当我最后一次使用PHP(几年前)时,我依稀记得做过这样的事情:

$firstVariable, $secondVariable = explode(' ', 'Foo Bar');

请注意,上述语法不正确,但在此示例中,它将“Foo”分配给$firstVariable,将“Bar”分配给$secondVariable。

正确的语法是什么?

谢谢。


答案 1
list($firstVar, $secondVar) = explode(' ', 'Foo Bar');

list() 是你所追求的。


答案 2

首先是几个单独使用 list() 的示例,然后是 2 个包含 list() 和 explode() 的示例。


PHP 手册页上的 list() 示例特别有启发性:

基本上,您的列表可以随心所欲地长,但它是一个绝对的列表。换句话说,数组中项目的顺序显然很重要,要跳过某些内容,您必须在list()中将相应的点留空。

最后,您无法列出字符串。

<?php

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";

// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL

?>

举几个例子:

应用 和 功能失调的关系:list()explode()Arrays

<?php
// What they say.
list($firstVar, $secondVar, , , $thirdVar) = explode(' ', 'I love to hate you');
// What you hear.
// Disaplays: I love you
echo "$firstVar $secondVar $thirdVar";
?>

最后,您可以将 list() 与数组结合使用。 将项目存储到数组中的最后一个槽中。应该注意存储内容的顺序,因为它可能与您期望的相反:$VARIABLE[]

<?php
list(, $Var[], ,$Var[] , $Var[]) = explode(' ', 'I love to hate you');
// Displays: 
// Array ( [0] => you [1] => hate [2] => love )
print_r($Var);
?>

为什么存储事物的顺序的解释与 list() 手册页上的警告中给出的一样:

list() assigns the values starting with the right-most parameter. If you are 
using plain variables, you don't have to worry about this. But if you are 
using arrays with indices you usually expect the order of the indices in 
the array the same you wrote in the list() from left to right; which it isn't.
It's assigned in the reverse order.