Logan Serman
Logan Serman

Reputation: 29880

PHP built-in function to assign each element of an array to a variable, does it exist?

For example:

$array = array('f', 'b');
assign($foo, $bar, $array);

// now $foo = 'f' and $bar = 'b'

Does something like this exist in the PHP language? I have never needed something like this before and cannot find anything that will do this.

I just wanted to make sure before I write the function myself - I don't want to write something that already exists within the language.

Upvotes: 0

Views: 239

Answers (3)

KingCrunch
KingCrunch

Reputation: 132011

list ($foo, $bar) = $array;

list() is something like the opposite of array() and its a language construct. Its especially important to know, that even if its listed in the functions reference of the manual (list()), it isn't, because no function is writeable.

Upvotes: 3

Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25755

you can use php's list() function

$array = array('f', 'b');
list($foo, $bar) = $array;

now it is

$foo = 'f' and $bar = 'b';

php.net/list

Upvotes: 1

simshaun
simshaun

Reputation: 21466

Pretty close to PHP's extract() function.

You need to specify the var name as they key for each value in the array though.

$array = array('foo' => 'f', 'bar' => 'b');
extract($array);
// now $foo = 'f' and $bar = 'b'

Upvotes: 1

Related Questions