Reputation: 877
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?
Upvotes: 10
Views: 32041
Reputation: 26016
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.
Upvotes: 5
Reputation: 522626
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.
Upvotes: 27