tags:

views:

135

answers:

5

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

+3  A: 

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';
}
Tesserex
A: 

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...

Coronatus
Actually, for arrays, curly braces are needed. Test it yourself.
Adrian
+5  A: 

Use references.

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

foreach($myArrays as &$arr) {
  $arr[] = 'newElement';
}
Tomalak
References aren't needed.foreach ($myArrays as $i => $arr) { $myArrays[$i][] = "foo"; }
Adrian
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.
Tesserex
A: 

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';
}
Rob
using a regular for loop instead of foreach seems needlessly confusing.
Tesserex
A: 

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';
}
ahmet2106