2

I've got an array

$variables_a = array(
   'a' => $a,
   'b' => $b,
   'c' => $c
);

and then another $variables_b = array('x','y','z') and I want to loop through the B array like so:

foreach($variables_b as $var) {
    $variables_c[] = array($var => $$var);
}

and then merge A & C together with $variables_combined = array_merge($variables_A, $variables_C)

The output I'm hoping to get is when I print_r is

Array
(
     [a] => a
     [b] => b
     [c] => c
     [x] => x
     [y] => y
     [z] => z
)

but what I get is

Array
(
     [a] => a
     [b] => b
     [c] => c
     [0] => Array
         (
            [x] => x
         )    
     [1] => Array
         (
            [y] => y
         )    
     [2] => Array
         (
            [z] => z
         )    
)

If I change $feature_variables[] = array($feature => $$feature) to $feature_variables = array($feature => $$feature) I get

Array
(
     [a] => a
     [b] => b
     [c] => c
     [z] => z
)

i.e. the last item from $variables_b but none of the others. So where am I going wrong?

5 Answers 5

4

Just do this :

$newvar = $variables_a;

foreach($variables_b as $var)
{
$newvar[$var] = $var;
}

$newvar will contain the array you want

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

Comments

3

Please loop through array c like:

foreach($variables_b as $var) {
    $variables_c[$var] = $$var;
}

Comments

2

Try this,

foreach($variables_b as $var) {
   $variables_c[$var] = $$var;
}

Comments

2
<?php

$variables_a = array(
   'a' ,
   'b' ,
   'c'
);

$variables_b = array('x','y','z');
 $variables_c=array();

foreach($variables_a as $var) {
    $variables_c[$var] =$var;

}

foreach($variables_b as $var) {
    $variables_c[$var] =$var;

}
print_r($variables_c);

?>
============
and test in : "http://codepad.org/1ICZxPIG"

Comments

1
$variables_a = array(
    'a' => $a,
    'b' => $b,
    'c' => $c
);
$variables_b = array('x','y','z');

foreach($variables_b as $var) {
$variables_c[$var] = $$var;
}


$variables_combined = array_merge($variables_a, $variables_c);

echo "<pre>";print_r($variables_combined);

Comments

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.