Pergunta

I want to convert this to ternary operator so I can simplify my codes..

<?php
  $checked = $value['chkboxvalue'] == 'ok' ? 'checked' : '';
  if(isset($_POST['chckbox'])):
      $checked = 'checked';
   elseif(count($_POST) > 0):
      $checked = "";
   endif;
?>
<input type="checkbox" name="chckbox" value="ok" <?=$checked?> />

and I tried this way.

<?php
$checked = $value['chckboxvalue'] == 'ok' ? 'checked' : '';
?>
<input type="checkbox" name="chckbox" value="ok" class="checkbox" <?=isset($_POST['chckbox']) ? 'checked' : (count($_POST) > 0 ? '' : 'checked')?> />

But it's not working :( any help? Thanks!

Foi útil?

Solução 2

Your count function is not closed correctly and instead of last 'checked' hardcoded value use $checked variable, try this:

<input type="checkbox" name="chckbox" value="ok" class="checkbox" <?= isset($_POST['chckbox']) ? 'checked' : (count($_POST)) > 0 ? '' : $checked ?> />

Outras dicas

Your syntax for ternary operation is wrong! Use this way:

$checked = ($value['chckboxvalue'] == 'ok') ? 'checked' : '';

And if you need to add an elseif condition, do this way:

$checked = ($value['chckboxvalue'] == 'ok') ? ((count($_POST) > 0) ? 'checked' : '') : '';
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top