除了错误和未定义的变量,您的函数可能会从一些重构中受益:
function gift_giver(array $people, array $gifts)
{
// take entry that will not overshoot either array
$entry = rand(0, min(count($people), count($gifts)) - 1);
printf(
'It was then that the gods reached out and decided to give %s the power of %s to aid in this quest.<br/><br/>',
$people[$entry],
$gifts[$entry]
);
}
gift_giver(['foo', 'bar'], ['baz', 'boo']);
// It was then that the gods reached out and decided to give bar the power of baz
// to aid in this quest.<br/><br/>
这样,您的函数仅负责生成包含来自两个数组的输入的文本。为您的具体情况量身定制:
gift_giver(
array($heroname, $friendname, $wizardname, "Captain Rumbeard", $frogname),
array("a magic compass", "the gift of no fear", "all seeing powers", "more rum", "a delightful lilly pad")
);
更新
看到两个数组是如何相关的,您还可以考虑将它们映射到一个数组中:
function gift_giver(array $people_gift_map)
{
$key = array_rand($people_gift_map);
printf(
'It was then that the gods reached out and decided to give %s the power of %s to aid in this quest.<br/><br/>',
$key,
$people_gift_map[$key]
);
}
gift_giver(array(
$heroname => "a magic compass",
$friendname => "the gift of no fear",
$wizardname => "all seeing powers",
"Captain Rumbeard" => "more rum",
$frogname => "a delightful lilly pad",
));