PHP 将数组分配给变量

问题描述 投票:0回答:3

我不确定我的记忆是否有误,但是当我上次使用 PHP 时(几年前),我隐约记得做了这样的事情:

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

请注意,上面的语法不正确,但在本例中,它将把“Foo”分配给$firstVariable,将“Bar”分配给$secondVariable。

正确的语法是什么?

谢谢。

php arrays list
3个回答
72
投票
list($firstVar, $secondVar) = explode(' ', 'Foo Bar');

list()就是你所追求的。


27
投票

从 php7.1 开始,你可以进行对称数组解构

https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetry-array-destructuring

代码:(演示

$array = [1, 2, 3];
[$a, $b, $c] = $array;
echo "$a $b $c";
// displays: 1 2 3

无需打电话

list()

这是在不声明临时变量的情况下“交换”元素位置时的新现代方法。 请参阅示例此处此处此处此处

有关深入的细分和示例,请仔细阅读这篇文章:https://sebastiandedeyne.com/the-list-function-and-practical-uses-of-array-destructuring-in-php/


至于将

explode()
list()
或数组解构一起使用,如果不能保证一定数量的元素, 最佳实践是声明
explode()
的第三个参数来限制生成元素的数量。 这不会强制生产那么多元素;相反,它只会告诉 php 当达到该元素数量时停止爆炸。

[$firstVariable, $secondVariable] = explode(' ', $stringToBeHalved, 2);

如果您不能 100% 确信分解的数据将为赋值运算符的另一端提供平衡的数据,您可以使用上述技术实现最大值,并使用

array_fill()
在右侧提供最小数量的元素赋值运算符的一侧。

代码:(演示

$strings = [
    "1,2,3,4",
    "1,2,3",
    "1,2"
];

$minElements = 3;
$defaultVal = null;

foreach ($strings as $string) {
    [$a, $b, $c] = array_pad(explode(',', $string, $minElements), $minElements, $defaultVal);
    var_export($a);
    echo ' _ ';
    var_export($b);
    echo ' _ ';
    var_export($c);
    echo "\n-----------------\n";
}

输出:

'1' _ '2' _ '3,4'
-----------------
'1' _ '2' _ '3'
-----------------
'1' _ '2' _ NULL
-----------------

事实上,对称数组解构甚至允许多次访问相同的元素/值——乍一看可能会感觉有点尴尬。

例如,您可以将单个值推送到两个数组中,如下所示:

[0 => $array1[], 0 => $array2[]] = ['zeroIndexedElement'];

阅读更多内容:解构数组时,可以多次访问相同的元素值吗?


还有一种很少被建议的技巧是调用

extract()
。如果您无法完全控制它正在处理的数据,此函数可能会很危险,因为它将把所有数据的键作为变量名推入全局范围 - 可能会覆盖变量并导致脚本漏洞或损坏。

要准备用于提取的数据,请通过分配键将索引数组转换为关联数组。

代码:(演示

$threeKeys = ['a', 'b', 'c'];
foreach ($strings as $string) {
    extract(array_combine($threeKeys, explode(',', $string, 3)));
    // now you can use $a, $b, and $c
}

上面的演示显示了未提供平衡/预期数据量时生成的一些警告。 因此,这个故事的寓意是要小心并通过确保数据处理器始终收到他们需要的内容来消除可能的边缘情况。


20
投票

首先是几个单独使用 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.
    
© www.soinside.com 2019 - 2024. All rights reserved.