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.
}
is this possible
Moderator: General Moderators
-
jaymoore_299
- Forum Contributor
- Posts: 128
- Joined: Wed May 11, 2005 6:40 pm
- Contact:
-
Bennettman
- Forum Contributor
- Posts: 130
- Joined: Sat Jun 15, 2002 3:58 pm
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'
}
}
?>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]);
}Code: Select all
if ($a > 0)
{
$which_one = $a;
}
elseif ($b > 0)
{
$which_one = $b;
}
else ($c > 0)
{
$which_one = $c;
}I believe the solution I've offered is fairly obvious/readable, and fast.
On a personal note, I don't see why someone would use arrays to do this...
Agree with Roja, use if-then-else for what it's intended to. My short version.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.
Code: Select all
$a = 1;
$b = 0;
$c = 0;
$which_one = ($a > 0 ? $a : ($b > 0 ? $b : ($c > 0 ? $c : '')));
echo $which_one;