How can split integer based on array keys and after that add values based on that how i split that integer

  arrays, php

I have array $money where key is money’s value but array key is – how much that type of money there are.
Here is example :

  $money = [
    1 => 5,
    2 => 2,
    5 => 1,
    10 => 4,
    20 => 2,
    50 => 3,
    100 => 1,
    200 => 1
];

where 1 = 0.1EUR, 2 = 0.2EUR and so go on till 200 where 200 = 2EUR. Key values are – how much coins i have.
After i’m getting exchange – itneger 95 and i need to split it up based on array keys, show how much and what kind of coins im getting and put those coins back in array.

I tried this way, but programm gives me back only 1 piece of every coin type if it is <= change

   if ($change > 0) {
      echo 'Your change is : '. $change;
      foreach (array_reverse($money, true) as $key => $amount) {
          if ($key <= $change) {
              echo 'Returned coin: ' . $key . PHP_EOL;
    }

And here is output where you can see that expected output is 95 but programm gives me 88

    In progress
    ***
    Your change is : 95
    Returned coin: 50
    Returned coin: 20
    Returned coin: 10
    Returned coin: 5
    Returned coin: 2
    Returned coin: 1

expected output would be:

    In progress
    ***
    Your change is : 95
    Returned coin: 1 x 50
    Returned coin: 2 x 20
    Returned coin: 1 x 5

something like that and after add them to my money array.

Source: Ask PHP

LEAVE A COMMENT