Search code examples
phpconditional-statements

I need to change a field number_format


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


Solution

  • 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), '.', '')