Actually, there's no need to check for ($i == 0) on each iteration.
function subtract() {
$num_args = func_num_args();
$arg_list = func_get_args();
$result = $arg_list[0]; //assume at least 1 argument passed
for ($i = 1; $i < $num_args; $i++) {
$result -= $arg_list[$i];
}
return $result;
}
EDIT:
Actually, the same mistake (not initialising $result) is made in your addition function.
It should be:
function add() {
$num_args = func_num_args();
$arg_list = func_get_args();
$result = $arg_list[0]; //assume at least 1 argument passed
for ($i = 1; $i < $num_args; $i++) {
$result += $arg_list[$i];
}
return $result;
}
If you want to take into account the possibility of no arguments passed:
function add() {
if (($num_args = func_num_args()) > 0) {
$arg_list = func_get_args();
$result = $arg_list[0];
for ($i = 1; $i < $num_args; $i++) {
$result += $arg_list[$i];
}
return $result;
} else {
return false;
}
}
Of course, instead of returning false, you could return 0, which may be more useful.