By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,967 Members | 1,684 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,967 IT Pros & Developers. It's quick & easy.

question about embeded PHP

P: 51
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:100%" id="terms">
<?php foreach($tes_terms 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
Oct 23 '08 #1
Share this Question
Share on Google+
3 Replies


Atli
Expert 5K+
P: 5,058
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:100%" id="terms">
<?php
foreach($tes_terms 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?
Oct 23 '08 #2

P: 51
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

Expand|Select|Wrap|Line Numbers
  1. <tr>
  2.     <td>Terms:</td>
  3.     <td><SELECT style="width:100%" id="terms">
  4.     <?php foreach($tes_terms as $desc => $val):?>
  5.         <?php $_my_selected = ($terms == $val? 'selected': 'Z');?>
  6.         <?php echo "<option value='$val' $_my_selected >$desc</option>";?>
  7.     <?php endforeach;?>
  8.     </SELECT></td>
  9.     <td class="err_red"></td>
  10. </tr>
Oct 24 '08 #3

P: 51
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
Oct 24 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.