简体   繁体   中英

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.

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".

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM