Mike Volmar
Mike Volmar

Reputation: 2093

How can I assign a number to access assigned array value?

I'm storing results in a multidimensional array, some values are identified by variables with a numeric value ex. $end1 = "2017-01-08"; Each date has about 10 categories under it that store a numeric value. I need to loop thru all the values under $end1 to get a total.

this works:

foreach($results[$key][$end1] as $type => $amount) {
    $total1 += $amount[$value];
}

but now I have a bunch of these foreach statements - one for each total I need - and I'd like to consolidate them into one block, but I am having trouble getting the variable name correct.

this does not work:

    for($i = 1; $i <= 4; $i++){
        $target = "\$end$i";
        $targettotal = "\$total$i";
        foreach($results[$key][$target] as $type => $amount) {
            $targettotal += $amount[$value];
        }            
    }

How do I fix/define $target and $targettotal so the array values are accessible?

Upvotes: 1

Views: 28

Answers (1)

Ali
Ali

Reputation: 3081

Have a look at the following demonstration, note the evaluation of $targetVarName in the next line by prepending it with another dollar sign.

<?php

$item1 = 'aaa';
$item2 = 'bbb';
$item3 = 'ccc';
$item4 = 'ddd';
$item5 = '333';

for ($i = 1; $i < 6; $i++) {

    $targetVarName = 'item' . $i;

    echo $targetVarName .' => '. $$targetVarName . "\n";
}

This will output something like:

item1 => aaa
item2 => bbb
item3 => ccc
item4 => ddd
item5 => 333

Upvotes: 2

Related Questions