Page 1 of 1

Correct syntax

Posted: Mon Sep 18, 2006 8:39 pm
by bob_the _builder
Hi,

Whats the correct format for:

Code: Select all

echo '<option '.$row['maincat_id'].' == $maincat ? 'selected' : '' value="'.$row['maincat_id'].'">'.$row['maincat_name'].'</option>';
Can't seem to get it right


Thanks

Posted: Mon Sep 18, 2006 8:42 pm
by feyd
Looks like you're missing a "'." and possibly a few parens.

Posted: Tue Sep 19, 2006 7:00 am
by ibbo
Whats the output you are after.

Using the shortcut $var == $other ? 'selected' : ''; wont quite work how your wanting it to.

Try

Code: Select all

$string = '<option';
$var == $other ? $string .= 'selcted': '';
$string .= "value={$row['maincat_id'}>{$row['maincat_name']}</option>'";

echo $string;
ibbo

Posted: Tue Sep 19, 2006 7:40 am
by CoderGoblin
Try

Code: Select all

echo "<option value=\"{$row['maincat_id']}\"".($row['maincat_id'] == $maincat ? 'selected' : '').">{$row['maincat_name']}</option>";
The if is simple... (condition ? true:false)

Posted: Tue Sep 19, 2006 7:40 am
by lecram

Code: Select all

echo '<option ';
if ($row['maincat_id'] == $maincat) {
echo 'selected value="'.$row['maincat_id'].'">'.$row['maincat_name'].'</option>';
} else {
echo 'value="something_else_or_default">something_else_or_default</option>';
}

is that what you are going for?

Posted: Tue Sep 19, 2006 11:12 am
by RobertGonzalez
It looks like you are looping through a set of some sort. If that is the case, you could do something like this...

Code: Select all

<?php
//Loop construct
{
    $maincat_id = $row['maincat_id'];
    $selected = ($maincat_id == $maincat) ? ' selected="selected"' : '';

    echo '<option value="' . $maincat_id . '"' . $selected . '>' . $row['maincat_name'] . '</option>';
}
?>

Posted: Mon Sep 25, 2006 3:21 am
by bob_the _builder
Cant get the following to work, I echoed out the variables and they contain the data needed:

Code: Select all

$selected = ($_GET['filter'] == $filter) ? ' selected="selected"' : '';

echo '<select name="filter">
        <option value="new"' . $selected . '>New</option>
        <option value="archived"' . $selected . '>Archived</option>
      </select>';

Should it be working?


Thanks

Posted: Mon Sep 25, 2006 5:04 am
by CoderGoblin
Brackets are wrong...

Code: Select all

$selected = ($_GET['filter'] == $filter ? ' selected="selected"' : '');
should work

or use

Code: Select all

$selected='';
if ($_GET['filter']== $filter) $selected='  selected="selected"';

Posted: Thu Sep 28, 2006 3:58 am
by RobertGonzalez
Those brackets were correct. Ternary syntax is:

Code: Select all

$var = (if_this) ? do_this : do_else;

Posted: Thu Sep 28, 2006 5:15 am
by onion2k

Code: Select all

echo "<select name=\"filter\">";
echo "<option value=\"new\"".(($_GET['filter']=="new")?" selected":"").">New</option>";
echo "<option value=\"archived\"".(($_GET['filter']=="archived")?" selected":"").">Archived</option>";
echo "</select>";