Jump to content

Archived

This topic is now archived and is closed to further replies.

Zipp425

Help with the || operator in a foreach loop

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?

Share this post


Link to post
Share on other sites
I don't think you can use [code]$aname == 'height' || 'width'[/code] You would need to use [code]$aname == 'height' || $aname == 'width'[/code]

Share this post


Link to post
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!

Share this post


Link to post
Share on other sites

×

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.