0

I have two php arrays

$arra = array('one', 'two', 'five', 'seven');

$arrb = array('black', 'white', 'gold', 'silver');

I need to create variables, like this way:

foreach ($arra as $el) {
    $el = $arrb[index of $el];
}

So echoing resulting variables:

echo $one should be black
echo $two should be white and so on.

How to do that?

2
  • 1
    extract(array_combine($arra, $arrb)); php.net/manual/en/function.extract.php Commented Sep 18, 2018 at 17:31
  • @splash58, it works, thanks. Commented Sep 18, 2018 at 17:59

3 Answers 3

2

Try with array_combine() and then use foreach() to make dynamic variables. array_combine()- Creates an array by using one array for keys and another for its values

<?php
 $arra = array('one', 'two', 'five', 'seven');
 $arrb = array('black', 'white', 'gold', 'silver');
 $result = array_combine($arra, $arrb);
 foreach($result as $key=>$value){
    ${$key} = $value;
 }
 echo $two;
?>

DEMO: https://3v4l.org/VPNQh

OR use extract() after combining $arra and $arrb. extracts()- Imports variables into the current symbol table from an array.

<?php
$arra = array('one', 'two', 'five', 'seven');
$arrb = array('black', 'white', 'gold', 'silver');
$result = array_combine($arra, $arrb);
extract($result, EXTR_PREFIX_SAME,'');
echo "$one, $two, $five, $seven";
?> 

DEMO: https://3v4l.org/VW55k

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

Comments

1

You can actually set a variable's name using a variables value, You need something like this:

for($x=0; $x < count($arra); $x++){
    $$arra[$x] = $arrb[$x];
}

Notice the double $$. This is not a mistake.

2 Comments

Glad I could help, what changed?
some typo in my code. it's ok now. where is a reference for double $, pls?
0

I think this is what you want:

$arra = array('one', 'two', 'five', 'seven');

$arrb = array('black', 'white', 'gold', 'silver');

foreach($arra as $key=>$ela) {
  $elb = $arrb[$key];
  ${$ela} = $elb;
}

echo $one;
echo $two;
echo $five;
echo $seven;

For using strings as variables I found this link helpful.

Comments

Your Answer

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