-1

I am a beginner in PHP and I have a such code.

<?php foreach ($statuses as $status) { ?>
    <div class="dropdown-item">
       <span data-status="<?php echo $status['id'] ?>" class="dropdown-item__sub <?php echo ($last_ticket['status'] ?? '') == $status['status'] ? ' active' : '' ?>"><?php echo $status['status'] ?></span>
    </div>
  <?php } ?>

Is it possible to write this expression in variable ? Like this ..

 $html .= '<span data-status=' . $status['id'] . ' class=' . 'dropdown-item__sub ' . ($last_ticket['status'] ?? '') == $status['status'] ? ' active' : ''  . '/>' . $status['status']. '</span>';

I try different way and it dose not work right.

  • Ok so what is wrong with it? Explain exactly what you wanted, and exactly what happened instead. "does not work" doesn't tell us anything useful about your problem. – ADyson May 19 '21 at 08:32
  • 1
    Does this answer your question? [Ternary operator and string concatenation quirk?](https://stackoverflow.com/questions/1317383/ternary-operator-and-string-concatenation-quirk) – El_Vanja May 19 '21 at 08:33
  • P.S. the answer to "is it possible" is "yes you can", but you just have to do it right – ADyson May 19 '21 at 08:34
  • You have also left out all the double quotes for the HTML attributes. – El_Vanja May 19 '21 at 08:34
  • ADyson, at final result I have empty data statuses and class 'active' dose not added. –  May 19 '21 at 08:36

2 Answers2

1

I think this is what you are looking for:

$html .= '<span data-status="' . $status['id'] . '" class="' . 'dropdown-item__sub ' . (($last_ticket['status'] ?? '') == $status['status'] ? ' active' : '')  . '"/>' . $status['status']. '</span>';

You needed to

a) make sure there are double-quotes around the HTML attributes, and

b) put brackets round your ternary operator to ensure the precedence of the operators is as you need it

Demo: http://sandbox.onlinephpfunctions.com/code/6f6135a1c3aaa88017857b2630879ff643a34822

ADyson
  • 57,178
  • 14
  • 51
  • 63
0

don't forget the '""'(double quote) on each attribute.

$html .= '<span data-status="' . $status['id'] . '" class="' . 'dropdown-item__sub ' . ($last_ticket['status'] ?? '') == $status['status'] ? ' active' : ''  . '/>"' . $status['status']. '</span>';