Jump to content

Help with the || operator in a foreach loop


Zipp425

Recommended Posts

Does anyone know why this
[code]
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>';
}
}
[/code]
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?
Link to comment
Share on other sites

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

if([i]expr[/i]){
  [i]stmts[/i]
}
[b]stmts[/b] will execute if [b]expr[/b] is true, easy enough.

if([i]expr_1[/i] || [i]expr_2[/i]){
  [i]stmts[/i]
}
[b]stmts[/b] will execute if [b]expr_1[/b] OR [b]expr_2[/b] is true. Still, easy enough.

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

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

Hope that helps you avoid it again!
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.