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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.