user723220
user723220

Reputation: 877

Combine two string arrays into an associative array

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

Answers (2)

Mukesh Chapagain
Mukesh Chapagain

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

deceze
deceze

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

Related Questions