Php foreach as a variable

I would like to use foreach for a loop, although a list of arrays 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 using $ {$ arrayName} [] the best way to do this? Is there another option instead of using curly braces? It currently works, but I'm just wondering if there is a better alternative.

thank

+3
source share
5 answers

Use links.

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

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

If you are stuck in this structure, I would say stick to what you do there. But the comment may be pleasant.

If you can make a difference, why not invest 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';
}
+5
source

.

$$arrayName[]

​​PHP?

, - ...

0

. - :

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

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

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

, :

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

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

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

Source: https://habr.com/ru/post/1747404/


All Articles