Page 1 of 1
is this possible
Posted: Sat Jun 04, 2005 11:47 pm
by jaymoore_299
in the situation where only one of $a, $b, $c is a positive value at a time, the others being zero,
if ($a||$b||$c)
{
$which_one = // the one variable found true, whichever it is.
}
Posted: Sun Jun 05, 2005 12:17 am
by hongco
your case would not work for it would be true if:
$a=$b=$c and none of them is a zero number.
or cases of 2 of them are equal and non-zero.
$a=$b
$b=$c
$a=$c .....
Posted: Sun Jun 05, 2005 2:34 am
by Bennettman
I'm low on sleep here, but you could do it more simply than a load of checks with arsort. It's a bit messy though.
Code: Select all
<?php
$a = 0;
$b = 5;
$c = 0;
$arr = array('a' => $a, 'b' => $b, 'c' => $c);
arsort($arr, SORT_NUMERIC); // orders to B, A, C
if (current($arr) > 0) // highest number is over 0
{
if (next($arr) == 0) // second-highest number is 0 (hence, assuming none are negative, the rest are also 0)
{
reset($arr);
$result = key($arr); // $result becomes 'b'
}
}
?>
Posted: Sun Jun 05, 2005 9:51 am
by Skara
That's a weird way to do it, IMO.
Code: Select all
$a = 0;
$b = 5;
$c = 0;
$arr = array('a' => $a, 'b' => $b, 'c' => $c);
arsort($arr, SORT_NUMERIC); // orders to B, A, C
if ($arr[0] > 0 && $arr[1] == 0) {
$result = key($arr[0]);
}
Posted: Sun Jun 05, 2005 11:59 am
by Roja
Code: Select all
if ($a > 0)
{
$which_one = $a;
}
elseif ($b > 0)
{
$which_one = $b;
}
else ($c > 0)
{
$which_one = $c;
}
You can also do it with a switch statement, or a number of other ways.
I believe the solution I've offered is fairly obvious/readable, and fast.
Posted: Mon Jun 06, 2005 5:17 am
by JAM
On a
personal note, I don't see why someone would use arrays to do this...
Roja wrote:You can also do it with a switch statement, or a number of other ways.
I believe the solution I've offered is fairly obvious/readable, and fast.
Agree with Roja, use if-then-else for what it's intended to. My short version.
Code: Select all
$a = 1;
$b = 0;
$c = 0;
$which_one = ($a > 0 ? $a : ($b > 0 ? $b : ($c > 0 ? $c : '')));
echo $which_one;