Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn array values into variables?

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?

like image 212
user723220 Avatar asked Apr 26 '11 06:04

user723220


1 Answers

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.

like image 154
Mukesh Chapagain Avatar answered Oct 10 '22 05:10

Mukesh Chapagain