tags:

views:

125

answers:

2

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 = explode(' ', 'Foo Bar');

Note that the above is incorrect syntax, however in this example it would assign 'Foo' to $firstVariable, and 'Bar' to $secondVariable.

What is the correct syntax for this?

Thanks.

+14  A: 
list($firstVar, $secondVar) = explode(' ', 'Foo Bar');

list() is what you are after.

Brad F Jacobs
+3  A: 

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.
Peter Ajtai