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
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).

Link to comment
Share on other sites

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/>';
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.