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

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.