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

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

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;       
        

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 :

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.

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