0

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.

1
  • A similar setting exists for requested variables register_globals but regardless of that I would strongly advise you not to do that. It makes it superbly harder to debug, and open all sorts of doors for hacking Commented Feb 24, 2012 at 18:35

3 Answers 3

3
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.

Sign up to request clarification or add additional context in comments.

4 Comments

Exactly what I was looking for, thank you :)! I had forgotten about list. Will accept as soon as I can.
Looking at the other answers it seems, that you are not alone. I'm a little bit surprised...
@KingCrunch, yeah, I've even used list, but my PHP is obviously getting a bit rusty.
I misread the question thinking it needed to happen to all variables within any dynamic array.
1

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'

Comments

1

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

2 Comments

It was probably because you tried to snipe the accepted answer by posting a very simple solution first, and then editing in more detail, even after your solution was already posted as an answer. Just a guess, it wasn't me!
@IbrahimAzharArmar, if there was a down-vote, it's been removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.