'PHP conditionally pass nested arrays as function argument

I got two nested index arrays, which I want to populate with values using a function.

But on a conditional basis: if this, populate the first array; if that, populate the second array.

Here is what I got:

WORKING, but repetitive

$sectionCounter = 0;

foreach($sections as $section) {
    if ($direction === 'up') {
        $array1[$sectionCounter][] = 1; 
        $array1[$sectionCounter][] = 25;
        // ...
    }   else {
        $array2[$sectionCounter][] = 1; 
        $array2[$sectionCounter][] = 25;
        // ...
    }
    $sectionCounter++;
}

PREFERRED (not working yet)

function addElements($temp, $sectionCounter) {
        $temp[$sectionCounter][] = 1; 
        $temp[$sectionCounter][] = 25;
        // ...
}

foreach($sections as $section) {
    if ($direction === 'up') {
        addElements($array1, $sectionCounter);
    } else { 
        addElements($array2, $sectionCounter);
    }
    $sectionCounter++;
}


Solution 1:[1]

You can try another approach instead

$sectionCounter = 0;
$data = [
   'up' => $array1,
   'other' => $array2
];
foreach($sections as $section) {
    $dir = $direction === 'up'? 'up': 'other';
    
    $data[$dir][$sectionCounter][] = 1; 
    $data[$dir][$sectionCounter][] = 25;
        // ...
   
    $sectionCounter++;
}

$array1 = $data['up'];
$array2 = $data['other'];


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 R4ncid