Forum Moderators: coopster

Message Too Old, No Replies

Exclude in Ternary Operator

php, echo, ternary

         

actolearn

8:01 pm on Apr 9, 2015 (gmt 0)

10+ Year Member



My DB table has a status column. Each product has status of active, sold or archives in that column.

Below ternary operator works but I need all "archives" products to be EXCLUDED from my web page.

<?php echo ($item["status"] == 'sold' ? 'Sold' : '' ); ?>


I've searched but can't find anything that applies...

lucy24

8:31 pm on Apr 9, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



So you're looking for a three-way split? Do one thing if it's "archives", another thing if it's "Sold" and a third thing if it's "active"? Conceptually (i.e. never mind about "else if"):
if "archives"
--do A
else
  if "sold"
  -- do B
  else
  -- do C
It is at this point that I would go to a "switch" construction, unless the actions for "sold" and "active" have a lot in common with each other and you don't want to duplicate code.

LifeinAsia

11:27 pm on Apr 9, 2015 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



From your other post [webmasterworld.com], using the "status=('active' OR 'sold')" in the query of your example should be doing that.
Although I would use "status IN ('active','sold')"

actolearn

4:14 pm on Apr 10, 2015 (gmt 0)

10+ Year Member



Although I would use "status IN ('active','sold')"

Thank you! Your suggestion fixed the problem. Now if product is marked "archives", the product no longer shows up on that web page BUT "active" and "sold" do show up.

default password

5:27 am on Apr 29, 2015 (gmt 0)

10+ Year Member



I would add that ternary operations need proper parenthesis, as this is more like what the code should be:

<?php echo ($item["status"] == 'sold') ? 'Sold' : ''; ?>
<?php echo (($item["status"] == 'sold') ? 'Sold' : ''); ?>

Both result in the same output, but most times ternary operations need the ()'s around expr1. (And for echo the ()' around it's argument is optional.)

REF: [php.net...]

d3vrandom

7:40 pm on May 1, 2015 (gmt 0)

10+ Year Member



Use switch case:


switch( $item['status'] ) {
case 'Sold':
echo "Sold";
break;
case 'archived':
continue; //assuming this is in a for loop
break;
}