Jump to content

Logic question with && and ||


dk4210

Recommended Posts

Hello guys,

 

I have a question about the logic of OR (||) and &&

 

I have a form and on the form is asks for hair color

 

<div class="hcenter"><div class="box3">Hair color</div></div>
	<div class="box2"><input type="radio" name="hair" value="Black" />Black<br />
        <input type="radio" name="hair" value="Brunette" />Brunette<br />
        <input type="radio" name="hair" value="Blonde" />Blonde<br />
        <input type="radio" name="hair" value="Red" />Red<br /></div>

 

I grab the post var  like this

 

$hair = $_POST['hair']; // I actually have it filtered but you get the point

 

I created this function

 

function check_Haircolor($hair){
if (isset($hair) && $hair != 'Brunette' || $hair != 'Black' ||  $hair != 'Red' || $hair != 'Blonde' ){				
	 Do something here

}

}

 

But it would not work correctly.. I kept doing the "Do something here...." so I tried the && and it worked (Se below) as expected. I would have bet that the or (||) would have been the correct code..

 

 

 


function check_Haircolor($hair){
if (isset($hair) && $hair != 'Brunette' && $hair != 'Black' &&  $hair != 'Red' && $hair != 'Blonde' ){				
	 Do something here

}

}

 

 

Why did the && word and not the ||

 

Thanks,

Dan

 

Link to comment
https://forums.phpfreaks.com/topic/235705-logic-question-with-and/
Share on other sites

if (isset($hair) && $hair != 'Brunette' || $hair != 'Black' ||  $hair != 'Red' || $hair != 'Blonde' ){

 

In English this would be;

 

if $hair is set (as MadTechie says, will always be true anyway) and $hair does not equal Brunette,

or if $hair does not equal black,

or if $hair does not equal red,

or if $hair does not equal blonde, ...

 

Even excluding the isset check, that statement would always evaluate to true.

Archived

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

×
×
  • 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.