0

I am trying to evaluate date[3] to determine selected option. All this is inside a php sql query. I am not able to find out an easy way to get a selected for the value returned in date[3] in my $options string variable.

<?php  //sql statement
    foreach( $db->query($sql) as $data ) {

        $options = "<select type='text' name='pagephone'  select id='pagephone' >
       <option value=''></option>
       <option ". if ($data[3] == 'vtext.com' ){ echo 'selected' };. " value='vtext.com'>Verizon Wireless</option>
       <option ". if ($data[3] == 'vmobl.com' ){ echo 'selected' };. " value='vmobl.com'>Virgin Mobile</option>
       <option ". if ($data[3] == 'sms.alltelwireless.com' ){ echo 'selected' };. " value='sms.alltelwireless.com'>Alltel</option>";
       ?>
3
  • 2
    Use the :? operator to put a conditional in an expression. Commented Feb 23, 2018 at 17:40
  • 1
    Curious, if creating a whole select for each db return is intentional or not. Commented Feb 23, 2018 at 17:53
  • IcredibleHat1. Since I could not figure it out I was going to use a if statement outside and hardcode the selected option. Would just have many of them..... bad way to code. Commented Feb 23, 2018 at 19:44

1 Answer 1

2

You're trying to concatenate a value with ., so the value you use needs to be an expression that evaluates to a string. An if block is not such an expression, as you can see from the syntax error you get if you use the code from your question. You can use a ternary expression instead, like this.

...<option ". ($data[3] == 'vtext.com') ? 'selected' : '' . " value='vtext.com'>
      Verizon Wireless</option>...

Personally, I would prefer to iterate an array of value/text pairs rather than hardcoding all the select options, like this:

$values = [
    'vtext.com' => 'Verizon Wireless',
    'vmobl.com' => 'Virgin Mobile',
    'sms.alltelwireless.com' => 'Alltel'
];

foreach( $db->query($sql) as $data ) {
    $options = "<select type='text' name='pagephone' id='pagephone'><option value=''></option>";

    foreach ($values as $value => $text) {
        $selected = ($data[3] == $value) ? 'selected' : '';
        $options .= "<option value='$value' $selected>$text</option>";
    }
    $options .= '</select>';
}

But that's just my opinion. Don't forget to close your <select>, though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.