Jump to content

[SOLVED] More elegant way of doing this?


johnny44

Recommended Posts

I have three numbers, $a, $b, $c. If all three are distinct, I want to display the lowest, middle and highest. I'm using this:

 

if( ($a==$b) || ($b==$c) || ($c==$a) )
{  
   echo "Ignore";
}
else
{
   $U = array($a,$b,$c);
   sort($U);
   echo "Lowest $U[0], Middle $U[1], Highest $U[2]";
}

 

Is there a more elegant way?

Link to comment
https://forums.phpfreaks.com/topic/95339-solved-more-elegant-way-of-doing-this/
Share on other sites

If you have only 3 numbers, I think that's fine.  If you have a large or unlimited quantity, then you might want to  use a generic duplicate checking algorithm (such as putting all the numbers as keys in an associative array, checking for duplicate keys first).

Here's one generic version

<?php 
$numbers = array(10,45,1,2,3,4,5,6,20);

if (array_unique($numbers) != $numbers) 
    echo "Ignore";
else {
    $k = count($numbers);
    sort($numbers);
    echo 'Low : ' . $numbers[0] . '<br/>';
    echo 'Middle : ' . $numbers[floor($k/2)] . '<br/>';
    echo 'High : ' . $numbers[$k-1] . '<br/>';
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.