<?php
 
error_reporting(-1);

$amount = 6600;
$bills = [5000, 2000, 500, 200];
$totalBills = [1, 4, 1, 3];
$rndCombination = [0, 0, 0, 0];
 
function nextCombination($total, $combination, $bills, $amount){
	$n = count($total) - 1;
	for( ; $n>=0; $n--){
		if($combination[$n] < $total[$n]){
			$combination[$n] += 1;
			break;
		} else {
			$combination[$n] = 0;
		}
	}
	return $combination;
}

function calculateSum($combination, $bills){
	$sum = 0;
	foreach($bills as $k => $v){
		$sum += $v * $combination[$k];
	}
	return $sum;
}

function outputCombination($combination, $bills){
	$str = "";
	foreach($bills as $k => $v){
		$str .= "{$v}x{$combination[$k]} ";
	}
	return $str;
}

$res = nextCombination($totalBills, $rndCombination, $bills, $amount);
$sum = calculateSum($res, $bills, $amount, $totalBills);

function Main($res, $sum, $amount, $totalBills, $bills){
	while($res != $totalBills){
		if($sum == $amount){
			$str = outputCombination($res, $bills);
			echo "Сумма: {$amount}\n";
			echo "Выдача возможна, число купюр:\n{$str}";
			exit();
		} else {
			$res = nextCombination($totalBills, $res, $bills, $amount);
			$sum = calculateSum($res, $bills, $amount, $totalBills);
		}
	}
	echo "Выдача невозможна, подходящей комбинации не нашлось.";
}

Main($res, $sum, $amount, $totalBills, $bills);
