0

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 :)

3
  • 5
    All keys of an array must be unique. You can’t have 5000 twice and 10000 ten times as the keys of an array. Commented Mar 3, 2014 at 1:34
  • What @SharanyaDutta said. Commented Mar 3, 2014 at 1:42
  • Hi @SharanyaDutta, thank you for your comment. May I ask if there is a better way to do it? The keys in the array represent the monthly target for sales and the value represents the fee accumulated so there is always a possibility of duplicate keys. I've tried lots of solutions so far and none have been effective so far. Thanks! Commented Mar 3, 2014 at 1:43

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow @sharanya thank you so much I really appreciate it! I went back and forward using for & while loops. You make it look easy. Thank you again for your answer, I'll definitely be sure to learn from it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.