if statement in the middle of concatenation? [closed]

Solution 1:

if is a self standing statement. It's a like a complete statement. So you can't use it in between concatenetion of strings or so. The better solution is to use the shorthand ternary operatior

    (conditional expression)?(ouput if true):(output if false);

This can be used in concatenation of strings also. Example :

    $i = 1 ;
    $result = 'The given number is'.($i > 1 ? 'greater than one': 'less than one').'. So this is how we cuse ternary inside concatenation of strings';

You can use nested ternary operator also:

    $i = 0 ;
    $j = 1 ;
    $k = 2 ;
    $result = 'Greater One is'. $i > $j ? ( $i > $k ? 'i' : 'k' ) : ( $j > $k ? 'j' :'k' ).'.';

Solution 2:

if..else is a statement and cannot be used inside an expression. What you want is the "ternary" ?: operator: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary.

Solution 3:

Use a shorthand if statement using ternary operators ?: -

$display = 'start ' . (($row['type']=="battle")? 'showB' : 'showA') . ' end ';

See "Ternary Operators" on http://php.net/manual/en/language.operators.comparison.php

Solution 4:

if is a statement. One cannot put statements inside an expression.

$str = 'foo';
if (cond)
{
  $str .= 'bar';
};
$str .= 'baz';