Home > OS >  How do I find the max of three numbers with a PHP function without using the max() function?
How do I find the max of three numbers with a PHP function without using the max() function?

Time:04-01

I'm trying to write a php function that will find the max number from three text input boxes. The assignment will not let me use the max() function.

Here is my php code. It should give me an output with the max number. "Max number entered is:"

$n1 = $_POST['n1'];
$n2 = $_POST['n2'];
$n3 = $_POST['n3'];

//process

    if($n1 > $n2 and $n1 > $n3){
        $n1=$max;
    }
    if($n2 > $n1 and $n2 > $n3){
        $n2=$max;
    }
    if($n3 > $n1 and $n3 > $n2){
        $n3=$max;
    }
 print "Max number entered is:" .$max;       
        

CodePudding user response:

Your assignments are the wrong way round: $max = $n1. Also if any of your inputs are the same, you're going to run into problems with that code.

You could also do:

print "Max number entered is:" . ( $n1 > $n2 && $n1 > $n3 ? $n1 : ( $n2 > $n3 ? $n2 : $n3 ) )

for a nice one-liner; it's cleaner, but you may be penalised for reduced readability.

See ternary operators.

CodePudding user response:

I suggest this different approach which would make your code cleaner and easier to maintain

$numbers = [$_POST['n1'],$_POST['n1'],$_POST['n3']];

$max = 0;
foreach ($numbers as $number) {
  if ($number > $max) {
    $max = $number;
  }
}

print "Max number entered is: " .$max;

CodePudding user response:

$result = array_reduce(
    [ $n1, $n2, $n3 ], 
    fn($carry, $value) => $value > $carry ? $value : $carry, 
    0
);
  • Related