1

I am trying to use the ternary operator in a string in PHP

"hard_copy"=>"<input type='checkbox' (($station->hard_copy==1)?'checked':'') name='station[]' id='hard-copy-$key' class='hard-copy' value='hardcopy-$station->id-1' >
<label for='hard-copy-$key' style='margin-left: 30%;'></label>",

but I am having probably some syntax error

Cid
  • 14,968
  • 4
  • 30
  • 45
saad nasim
  • 13
  • 3

2 Answers2

1

I Will answer as I understand the question
as @Magnus Eriksson mentioned " You can't unpack statements inside double-quoted strings like that, only variables. You need to use concatenation. "
try this one

"hard_copy"=>
"<input type='checkbox' ". (($station->hard_copy==1) ? 'checked' : '') . "name='station[]' id='hard-copy-$key' class='hard-copy' value='hardcopy-$station->id-1' >
<label for='hard-copy-'".$key." style='margin-left: 30%;'></label>",

S.Sachith
  • 536
  • 1
  • 9
  • 21
0

Try this using concatenation:

"hard_copy"=> "<input type='checkbox' ". ($station->hard_copy==1 ? 'checked':'' )." name='station[]' id='hard-copy-".$key."' class='hard-copy' value='hardcopy-".$station->id."-1' ><label for='hard-copy-".$key."' style='margin-left: 30%;'></label>",
Harshit Rastogi
  • 1,996
  • 1
  • 10
  • 19
  • 2
    You also need to add parentheses around the statement: `" . ($station->hard_copy == 1 ? 'checked' : '') . "`. – M. Eriksson Sep 02 '21 at 08:13