is this possible

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jaymoore_299
Forum Contributor
Posts: 128
Joined: Wed May 11, 2005 6:40 pm
Contact:

is this possible

Post 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.
}
hongco
Forum Contributor
Posts: 186
Joined: Sun Feb 20, 2005 2:49 pm

Post 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 .....
Bennettman
Forum Contributor
Posts: 130
Joined: Sat Jun 15, 2002 3:58 pm

Post 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'
  }
}

?>
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post 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]);
}
Roja
Tutorials Group
Posts: 2692
Joined: Sun Jan 04, 2004 10:30 pm

Post 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.
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

On a personal note, I don't see why someone would use arrays to do this... 8O

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;
Post Reply