PHP if statement inside string value

I'm not sure this is even possible. If it is I don't know how to do it.

$input = '<input type="text" name="'.$name.'" value="'.$value.'" '. if($edit == "no"){ echo "readonly"; } .'>';

3 answers

  • answered 2018-02-13 00:22 TCooper

    The way you're doing this, no.

    try

    if($edit == "no"){ $inputAppend = "readonly"; }
    else { $inputAppend = ""; }
    
    $input = '<input type="text" name="'.$name.'" value="'.$value.'" '.$inputAppend.'>';
    

    Or, if you want to keep it to one line, the ternary operator suggested by Ilya Bursov is the way to go.

  • answered 2018-02-13 00:23 Ilya Bursov

    you cannot use if, but you can use ternary operator, like this:

    $input = '<input type="text" name="'.$name.'" value="'.$value.'" '. (($edit == "no") ? "readonly" : "") .'>';
    

  • answered 2018-02-13 00:46 Tim Morton

    In an effort to get away from the "'.$var.'" confusion, you may prefer one of these alternatives:

    sprintf

    $input = sprintf("<input type='text' name='%s' value='%s'%s />",
                     $name,
                     $value,
                     $edit=='no' ? 'readonly' : ''
                    );
    

    or

    heredoc

    $readonly = $edit=='no' ? 'readonly' : '';
    
    $input = <<<INPUT
    <input type="text" name="$name" value="$value"$readonly />
    INPUT;
    

    but my preferred way is to be sure that you do your php calculation stuff first, then when that's all done, switch out of php and just write out the html:

    php as template

    <?php
    // do stuff
    // assign $name, $value, and $readonly
    ?>
    <html>
    <!-- html stuff -->
    <input type="text" name="<?= $name ?>" value="<?= $value ?>" <?= $readonly ?> />