How can I run a PHP IF clause within this already working PHP without breaking it?

Viewed 31

This is like inception trying to run PHP within PHP and I'm stuck.

I have a working line of code

$select1.='<option value="'.$rss['po_number'].'">'.$rss['po_number'].'</option>';

I want to have an option selected if a certain MySQL value matches the option value.

Such as:-

$select.='<option value="'.$rs['su_name'].'"' if('.$rs['su_name'].'==='.$row['xero_supplier'].') echo 'selected="selected">'.$rs['su_name'].'</option>';

But I can't for the life of me work out how to make this work and my brain is fried.

2 Answers

I HIGHLY recommend breaking this into several lines of php code just for your sanity. Trying to cram too much logic into a single line leads to cognitive overload, and the whole point of code is to make machine logic human readable.

Consider:

  $select.='<option value="'.$rs['su_name'].'"';
  if ($rs['su_name'] === $row['xero_supplier']) {
     $select.=' selected="selected"';
  }
  $select.='>'.$rs['su_name'].'</option>';

This is building out this particular option html tag. It starts the tag to look like:

<option value="somevalue"

And then IF that condition is true adds to make it looks like:

<option value="somevalue" selected="selected"

And then finally ends the tag to make it look like:

<option value="somevalue" selected="selected">some_su_name</option>
Related