Question

I have a variable which is:

$sum = 42500;

I have an array that looks like this:

$targetsarray = array(
    '5000' => '',
    '5000' => '',
    '10000' => '',
    '10000' => '',
    '10000' => '',
    '10000' => '',
    '10000' => '',
    '12000' => '',
    '12000' => '',
    '15000' => '',
    '15000' => '',
    '15000' => '',
};

The key inside the $targetsarray is generated dynamically from the database so it in fact looks like this:

$targetsarray = array(
    $targets => '',
};

What I would like to achieve in the array is to subtract the $sum value by each consecutive key in the array so that the final $targetsarray looks like this:

$sum = 45000;

$targetsarray = array(
    '5000' => '40000', // subtract 5000 from 45000
    '5000' => '35000', // subtract 5000 from 40000
    '10000' => '25000', // subtract 10000 from 35000
    '10000' => '15000', // subtract 10000 from 25000
    '10000' => '5000', // subtract 10000 from 15000
    '10000' => '0', 
    '10000' => '0',
    '10000' => '0',
    '10000' => '0',
    '10000' => '0',
    '10000' => '0',
    '10000' => '0',
};

Is there anyway that I can subtract the $sum from each key in the $targetsarray? Your help will be highly appreciated from an array noobie :)

Was it helpful?

Solution

You may simply have two arrays:

$targetsarray = array(5000, 5000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000);
$anotherarray = array();
$sum = 45000;
foreach($targetsarray as $val){
$anotherarray[] = $sum = ($sum >= $val) ? $sum-$val : 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top