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

Advertisements

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;       
        

>Solution :

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.

Leave a ReplyCancel reply