I am trying loop over a set of numbers if I inputted them into the terminal. By calling
php scripts/max.php 1 5 9
I want a loop that loops over 1, 5, 9 and tells me what the largest number is. I have been throughingly confused with loops but I got this far.
$args = $argv;
array_shift($args);
if (empty($args)) {
echo "Expecting numbers as arguments." . PHP_EOL;
exit(1);
}
$largest = [];
while ( $args ) {
echo $args . PHP_EOL;
while($args > $largest) {
break 2;
}
}
The idea is the loop would take any amount of numbers when inputting them in the terminal and tell me which number is the largest.
CodePudding user response:
Throw away all your loops and just do max($args)
1
Your code consists of way too much errors:
$args
is array, so$args
and$args > $largest
makes no sense and it's acting on hidden type cast of array$largest = [];
should be integer, not array.- You never assign anything to be
$largest
If that's school assignment, then do it proper way:
$args = $argv;
array_shift($args);
if (empty($args)) {
echo "Expecting numbers as arguments." . PHP_EOL;
exit(1);
}
$largest = PHP_INT_MIN; // first set it to be smallest possible integer. And since $args is not empty, we will overwrite it
foreach ($args as $arg) {
// Compare if current element is larger than our current $largest
if ($arg > $largest) {
$largest = $arg;
}
}
echo "Largest number: {$largest}";