10

I have two arrays. Like:

Bear, prince, dog, Portugal, Bear, Clown, prince, ...

and a second one:

45, 67, 34, 89, ...

I want to turn the string keys in the first array into variables and set them equal to the numbers in the second array.

Is it possible?

2 Answers 2

26
extract(array_combine($arrayKeys, $arrayValues));

http://php.net/array_combine
http://php.net/manual/en/function.extract.php

I'd recommend you keep the values in an array though, it's rarely a good idea to flood your namespace with variable variables.

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

4 Comments

So much better than the old days when you used to have to use eval for this sort of problem.
@Wes How old are these "old days"? PHP could do it without evil() since it had loops and variable variables... :)
I guess old days in my time was before I knew about extract which was pre 4.3. Just shows what I know I guess. evil()...nice :)
@chapagain Neither is better, really. The values should stay in an array... :)
5

Try using array_combine :-

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

Output:-

Array (
    [green]  => avocado
    [red]    => apple
    [yellow] => banana 
    )

Loop through this array and create variable for each key value:-

foreach($c as $key => $value) {
    $$key = $value;
}

Now, you can print the variables like:-

echo $green." , ".$red." , ".$yellow;

Hope this helps. Thanks.

2 Comments

I think using extract function is better way. php.net/manual/en/function.extract.php But if in case, you don't want all your array values as variables (want limit variables only) then you can use my answer.
For limiting variables, I'd go with extract(array_intersect_key($c, array_flip(array('green', 'red'))));. ;)

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.