admin管理员组

文章数量:1318573

I need your help. I have this code that I need to change

$metMessage = "";
        foreach($batches as $batch)
        {
            $metMessage .= '<tr>
            <td>' . $batch['comp_code'] . '</td>
            <td>' . $batch['description'] . '</td>
            <td>' . number_format($batch['quantity'], 0, '.', '') .'</td>
            </tr>';
        }

What i need:

If $batch['quantity'] < 3 then . 
    number_format($batch['quantity'], 2, '.', '') .'
else . 
    number_format($batch['quantity'], 0, '.', '') .'

I don't know how to add this condition

I need your help. I have this code that I need to change

$metMessage = "";
        foreach($batches as $batch)
        {
            $metMessage .= '<tr>
            <td>' . $batch['comp_code'] . '</td>
            <td>' . $batch['description'] . '</td>
            <td>' . number_format($batch['quantity'], 0, '.', '') .'</td>
            </tr>';
        }

What i need:

If $batch['quantity'] < 3 then . 
    number_format($batch['quantity'], 2, '.', '') .'
else . 
    number_format($batch['quantity'], 0, '.', '') .'

I don't know how to add this condition

Share Improve this question edited Jan 21 at 11:29 ADyson 62.1k16 gold badges78 silver badges91 bronze badges Recognized by PHP Collective asked Jan 21 at 10:52 user21024361user21024361 32 bronze badges 4
  • 1 "I don't know how to add this condition" - What have you tried? Where are you actually stuck? Are you receiving any errors? Are you receiving the wrong output? Please have a look at the tour and How to Ask – DarkBee Commented Jan 21 at 10:56
  • 1 You are within a string concatenation context there, so you can not use if/else in there directly. You could use the ternary operator, or split this into multiple parts (so that you can use an if/else in between.) Or you could use a variable for the second parameter of number_format, and then simply set that variable to the appropriate 2 or 0, before the whole $metMessage .= ... – C3roe Commented Jan 21 at 11:09
  • It looks You need to use the ternary operator: php/manual/en/… – Michas Commented Jan 21 at 13:10
  • thank you ALL for your comments, much appreciated! – user21024361 Commented Jan 21 at 16:32
Add a comment  | 

1 Answer 1

Reset to default 2

One way to do this neatly within the concatentation you've already got is using a ternary operator rather than an if/else block.

For example:

number_format($batch['quantity'], ($batch['quantity'] < 3 ? 2 : 0), '.', '')

本文标签: phpI need to change a field numberformatStack Overflow