question about embeded PHP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • datactrl
    New Member
    • Jul 2008
    • 51

    question about embeded PHP

    Hi, all

    I tried to set a default value on a 'select' object. Anyway, it seems the 'if' always return false. No one option is selected as I traced it. And I'm pretty sure there should be one value equals to the terms. Please help!

    [PHP]<tr>
    <td>Terms:</td>
    <td><SELECT style="width:10 0%" id="terms">
    <?php foreach($tes_te rms as $desc => $val):?>
    <?php if($terms == $val):?>
    <?php $_my_selected = 'selected';?>
    <?php else:?>
    <?php $_my_selected = '';?>
    <?php endif;?>
    <?php echo "<option value='$val' $_my_selected> $desc</option>";?>
    <?php endforeach;?>
    </SELECT></td>
    <td class="err_red" ></td> [/PHP]


    jack
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi Jack.

    What is the value of $terms? I don't see you set it anywhere.

    Also, if I may make a suggestion:
    [PHP]<tr>
    <td>Terms:</td>
    <td><SELECT style="width:10 0%" id="terms">
    <?php
    foreach($tes_te rms as $desc => $val) {
    $_my_selected = ($terms == $val ? 'selected' : '');
    echo "<option value='$val' $_my_selected> $desc</option>";
    }
    ?>
    </SELECT></td>
    <td class="err_red" ></td> [/PHP]
    It's exactly like your code, except without all the opening and closing <?php ?> tags and I replaced the if statement with a so called "ternary conditional operator" (read about that here)
    That is; a: "bool ? true : false" statement, where the "bool" is an expression, and if it is evaluated as true, the "true" part is executed. Otherwise the "false" part is executed.

    Much easier to read, don't you agree?

    Comment

    • datactrl
      New Member
      • Jul 2008
      • 51

      #3
      I changed like the following. The problem is the same. It created Z="" as an attribute for all options.

      $tes_terms is an array ('a'=>'1', 'b'=>2, 'c'=>3)
      terms's value is 2
      I use CI framework. so following is used to send it out
      $this->parser->parse('my_view ', $ar);
      $ar, associative array, contains $tes_terms and terms

      Code:
      <tr>
      	<td>Terms:</td>
      	<td><SELECT style="width:100%" id="terms">
      	<?php foreach($tes_terms as $desc => $val):?>
      		<?php $_my_selected = ($terms == $val? 'selected': 'Z');?>
      		<?php echo "<option value='$val' $_my_selected >$desc</option>";?>
      	<?php endforeach;?>
      	</SELECT></td>
      	<td class="err_red"></td>
      </tr>

      Comment

      • datactrl
        New Member
        • Jul 2008
        • 51

        #4
        HI, Atli

        Ok, I found the problem where is the value of $terms is followed by a CR I didn't realize before. Anyway thank you for your advice which is much easier to code and read.

        Jack

        Comment

        Working...