Jump to content

Ternary operator


soycharliente

Recommended Posts

Can you follow this?

<select name="Month">
<option value="">Month</option>
<?php
$i = 1;
while ($i <= 12)
{
$selected = ($picked) ? '' : ((isset($ymd)) ? (($m == $i) ? ' selected="selected"' : '') : ((date('m') == $i) ? ' selected="selected"' : ''));
$picked = (empty($selected)) ? FALSE : TRUE;
echo '<option value="'.$i.'"'.$selected.'>'.date('F', mktime(0,0,0,$i++)).'</option>';
}
?>
</select>

 

Also, as you can see, the second ternary is executed if nothing has been picked. But let's say the first option matches, $picked is set to TRUE, and the second one doesn't, $picked goes back to being FALSE. What can I do to make it not run anymore once $picked has been set to TRUE.

Link to comment
https://forums.phpfreaks.com/topic/168183-ternary-operator/
Share on other sites

The whole point of your $picked variable is to optimize out repeated executions of that first line in the loop, right?

 

If that's the case I'd say don't bother.  The loop executes 12 times and doesn't do anything so computationally expensive that you need to optimize out a big chunk.

 

Anyways I'd just write it like this:

<?php
$select = '
<select name="Month">
    <option value="">Month</option>';
$selectedMonth = isset( $ymd ) ? $m : date( 'm' );
for( $i = 1; $i <= 12; $i++ ) {
    $select .= sprintf( '<option value="%s"%s>%s</option>', 
        $i, $i == $selectedMonth ? ' selected="selected' : '', 
        date( 'F', mktime( 0, 0, 0, $i ) ) );    
}

?>

 

Link to comment
https://forums.phpfreaks.com/topic/168183-ternary-operator/#findComment-887035
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.