Jump to content


Photo

Help with the || operator in a foreach loop


  • Please log in to reply
3 replies to this topic

#1 Zipp425

Zipp425
  • Members
  • PipPip
  • Member
  • 18 posts

Posted 13 September 2006 - 03:54 PM

Does anyone know why this
foreach($xml->$parentNode->$childSelector->attributes() as $aname => $avalue){
if ($aname == 'height' || 'width'){
$dimensions .= '<div><input type="text" id="'.$childSelector.$aname.'" value="'.$avalue.'" /><label>'.$aname.'</label></div>';
}
}
is capturing all the $aname and $avalues, and not just the "height" or "width" $aname and $avalue?

When I do it without the OR operator, it works fine, and only captures the $aname and $avalue I want.

Is there a different operator I should use?

#2 Daniel0

Daniel0
  • Staff Alumni
  • Advanced Member
  • 11,956 posts

Posted 13 September 2006 - 03:56 PM

I don't think you can use
$aname == 'height' || 'width'
You would need to use
$aname == 'height' || $aname == 'width'


#3 Zipp425

Zipp425
  • Members
  • PipPip
  • Member
  • 18 posts

Posted 13 September 2006 - 04:28 PM

Works great now. Thank you very much.

#4 roopurt18

roopurt18
  • Staff Alumni
  • Advanced Member
  • 3,749 posts
  • LocationCalifornia, southern

Posted 13 September 2006 - 06:40 PM

Without clarification as to why it wasn't working, you may run into a similar problem down the road.  So here it is:

if(expr){
  stmts
}
stmts will execute if expr is true, easy enough.

if(expr_1 || expr_2){
  stmts
}
stmts will execute if expr_1 OR expr_2 is true. Still, easy enough.

In your case above, expr_1 was:
$aname == 'height'
and expr_2 was:
'width'

So expr_1 will only be true when $aname is the string 'height'.  However, expr_2 will always be true because a string is a non-zero value.

Hope that helps you avoid it again!

PHP Forms : Part I | Part II

JavaScript: Singleton

http://www.rbredlau.com




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users