Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

while algorithm loop in php

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Throw away all your loops and just do max($args)1


Your code consists of way too much errors:

  1. $args is array, so $args++ and $args > $largest makes no sense and it’s acting on hidden type cast of array
  2. $largest = []; should be integer, not array.
  3. 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}";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading