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

Time:07-30

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.

CodePudding user response:

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>

CodePudding user response:

Check out the PHP Ternary operator https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

it allows you to write

if (a){
  return b;
} else {
  return c;
}

as

return a ? b : c

It would allow your code to become as such

$select.='<option value="'.$rs['su_name'].'" '.($rs['su_name'] === $row['xero_supplier'] ? 'selected="selected"' : '').'>'.$rs['su_name'].'</option>';
  •  Tags:  
  • php
  • Related