开发者

php foreach as variable

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 thi开发者_如何转开发s? Is there another option rather than using curly braces? It currently works but I'm just wondering if there is a better alternative.

Thanks


Use references.

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

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


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


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜