3

I'd like to use foreach to loop though an array list and add an element to each array.

$tom = array('aa','bb','cc');
$sally = array('xx','yy','zz');

$myArrays = array('tom','sally');

 foreach($myArrays as $arrayName) {
     ${$arrayName}[] = 'newElement';
 }

Is the use of ${$arrayName}[] the best way to do this? Is there another option rather than using curly braces? It currently works but I'm just wondering if there is a better alternative.

Thanks

5 Answers 5

9

Use references.

$myArrays = array(&$tom, &$sally);

foreach($myArrays as &$arr) {
  $arr[] = 'newElement';
}
Sign up to request clarification or add additional context in comments.

2 Comments

References aren't needed. foreach ($myArrays as $i => $arr) { $myArrays[$i][] = "foo"; }
it's still a reference stored in $myArrays, otherwise $myArrays[$i] will be copies of $tom and $sally instead of the originals. Technically, it will hold the originals until they are changed, at which point php will copy them.
5

If you're stuck to that structure, I would say stick to what you're doing there. But a comment might be nice.

If you can rearrange things, why not nest them?

$tom = array('aa','bb','cc');
$sally = array('xx','yy','zz');

$myArrays = array(&$tom, &$sally); // store the actual arrays, not names

// note the & for reference, this lets you modify the original array inside the loop
foreach($myArrays as &$array) {
    $array[] = 'newElement';
}

Comments

0

No curly braces needed.

$$arrayName[]

The original line is maybe a bug in PHP?

Although I wonder why you would ever need to do this anyway...

1 Comment

Actually, for arrays, curly braces are needed. Test it yourself.
0

Some people will scold you for using variable variables. You could do something like this:

$tom = array('aa','bb','cc');
$sally = array('xx','yy','zz');

$myArrays = array(&$tom, &$sally);

for($i=0; $i<sizeof($myArrays); ++$i) {
    $myArrays[$i][] = 'newElement';
}

1 Comment

using a regular for loop instead of foreach seems needlessly confusing.
0

Not tried, but should work, too:

$tom = array('aa','bb','cc');
$sally = array('xx','yy','zz');

$myArrays = array('tom','sally');

foreach($myArrays as $key => $value) {
    $$value[] = 'newElement';
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.