I\'m not sure if my memory is wrong, but when I last used PHP (years ago), I vaguely remember doing something like this:
$firstVariable, $secondVariable = ex
First a few examples with list() alone, then 2 examples with list() combined with explode().
The examples on the PHP manual page for list() are especially illuminating:
Basically, your list can be as long as you want, but it is an absolute list. In other words the order of the items in the array obviously matters, and to skip things, you have to leave the corresponding spots empty in your list().
Finally, you can't list string.
<?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
?>
A few cases by example:
Applying list()
, explode()
and Arrays
to dysfunctional relationships:
<?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";
?>
Finally, you can use list() in conjunction with arrays. $VARIABLE[]
stores an item into the last slot in an array. The order things are stored should be noted, since it's probably the reverse of what you expect:
<?php
list(, $Var[], ,$Var[] , $Var[]) = explode(' ', 'I love to hate you');
// Displays:
// Array ( [0] => you [1] => hate [2] => love )
print_r($Var);
?>
The explanation of why the order things are stored in is as it is is given in the warning on the list() manual page:
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.
list($firstVar, $secondVar) = explode(' ', 'Foo Bar');
list() is what you are after.
From php7.1, you can do Symmetric array destructuring.
https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring
Code: (Demo)
$array = [1, 2, 3];
[$a, $b, $c] = $array;
echo "$a $b $c";
// displays: 1 2 3
Without calling list()
.
For in-depth breakdown and examples, have a long look at this post: https://sebastiandedeyne.com/the-list-function-and-practical-uses-of-array-destructuring-in-php/
As for using explode()
with list()
or array destructuring, if you are not guaranteed a certain number of elements,
it is best practice to declare the 3rd parameter of explode()
to limit the number of generated elements. This will not force the production of so many elements; rather it will merely tell php to stop exploding when that number of elements is achieved.
[$firstVariable, $secondVariable] = explode(' ', $stringToBeHalved, 2);
If you aren't 100% assured that your exploded data will provide balanced data to the other side of the assignment operator, you can implement a maximum with the technique above and use something akin to array_replace()
to provide a minimum number of elements on the right side of the assignment operator.
Code: (Demo)
$strings = [
"1,2,3,4",
"1,2,3",
"1,2"
];
$minElements = 3;
$defElements = array_fill(0, $minElements, null);
foreach ($strings as $string) {
[$a, $b, $c] = array_replace($defElements, explode(',', $string, $minElements));
var_export($a);
echo ' _ ';
var_export($b);
echo ' _ ';
var_export($c);
echo "\n-----------------\n";
}
Output:
'1' _ '2' _ '3,4'
-----------------
'1' _ '2' _ '3'
-----------------
'1' _ '2' _ NULL
-----------------
And one more technique that is very seldom advised is to call extract()
. This function can be dangerous if you don't have complete control of the data that it is processing because it will push all of the data's keys into the global scope as variable names -- potentially overwriting variables and leading to script vulnerability or breakage.
To prepare the data for extraction, convert the indexed array into an associative array by assigning keys.
Code: (Demo)
$threeKeys = ['a', 'b', 'c'];
foreach ($strings as $string) {
extract(array_combine($threeKeys, explode(',', $string, 3)));
// now you can use $a, $b, and $c
}
The above demo shows some of the Warnings generated when not providing balanced/expected volumes of data. So the moral of this story is to be careful and eliminate possible fringe cases by ensuring the data processors will always receive what they require.