user1227914
user1227914

Reputation: 3514

The easiest way to handle IF / OR in PHP while outputting inside HTML?

I have a PHP script that has outputs like these:

$dashboard_output = '';

(if / else statements here)

$dashboard_output .= '';

(more if / else statements here)

$dashboard_output .= '';

An example output would be:

$dashboard_output .= '<div>You have '.$orders_count.' orders.</div>';

Now, I want to write "order" if there's 1 order and "orders" if there's multiple orders.

The way I do it now is:

if ($orders_count >1){
  $s = 's';
}
$dashboard_output .= '<div>You have '.$orders_count.' order'.$s.'.</div>';

I know, feel free to have a laugh. But is there an easier way to do this within the $dashboard_output tags? Because as far as I know I can't do an if/else within that output line.

Upvotes: 0

Views: 28

Answers (2)

Karl Monson
Karl Monson

Reputation: 1

I personally would do it with an inline if/else statement:

$dashboard_output = '<div>You have '.$orders_count.' '.($orders_count >1 ? 'orders' : 'order').'.</div>';

Hope this helps you!

Upvotes: 0

kainaw
kainaw

Reputation: 4334

If it is strictly an if/else issue, you can use the ?

$dashboard_output.= '<div>You have '.$orders_count.' order'.($order_count>1 ? 's' : '').'</div>';

The ? is a quick way to do an if/else. It is "condition" ? "true result" : "false result".

Upvotes: 3

Related Questions