简体   繁体   中英

PHP ternary operator

I have 2 ternary operator as below:

1. (($_POST['movietype'] == $row1['id'])?'selected="selected"':'');
2. (($row1['id'] == $row['type'])?'selected="selected"':'');

Below are my output:

echo '<option value="'.$row1['id'].'"'.[HERE].'>'.$row1['label'].'</option>';

My question is how do I combine these 2 ternary operator into [HERE] section?

It's just 2 conditions for the same thing that you can even combine in one condition if you use in_array() .

So something like:

$class = ($_POST['movietype'] == $row1['id'] || $row1['id'] == $row['type'])
            ? 'class="selected"' : '';

or:

$class = in_array($row1['id'], array($_POST['movietype'], $row1['id']))
            ? 'class="selected"' : '';

and:

echo '<option value="'.$row1['id'].'" '.$class.'>'.$row1['label'].'</option>';

Following your same code, you can do something like this:

    $isSelected = ($_POST['movietype'] == $row1['id'] || $row1['id'] == $row['type']) 
                   ? 'selected="selected"' : '';

Then you can replace the [HERE] section as the following:

echo '<option value="'.$row1['id'].'" '.$isSelected.'>'.$row1['label'].'</option>';

By the way, i recommend you to use If...Else .

I would suggest creating a function that you can pass a unlimited # of values to that could trigger the option to be selected

/**
* @param id
* @param matches...
**/
function selectOpt() {
    $args = func_get_args();
    $id = array_shift($args);
    foreach($args as $a) {
        if($a === $id) {
            return 'selected="selected"';
        }
    }

    return '';
}

Then you can call it like this:

echo '<option value="'.$row1['id'].'"'. selectOpt($row1['id'], $_POST['movietype'], $row['type']) .'>'.$row1['label'].'</option>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM