Here is my solution:
<?php
$train = explode(" ", readline());
$capacity = readline();
$input = readline();
while ($input != "end") {
$args = explode(" ", $input);
$command = $args[0];
if ($command == "Add") {
$wagon = $args[1];
array_push($train, $wagon);
} else {
for ($i = 0; $i < count($train); $i++) {
if ($command + $train[$i] <= $capacity) {
$train[$i] += $command;
break;//the break; is needed: otherwise it will continue adding to the other wagons of the train as well
}
}
}
$input = readline();
}
echo implode(" ", $train);