0

I want to check two variables a and b and assign both the variable to new variable "c" and want to get the OR result from both the variables. for example if a=1 and b=0, c must be 1, while if a=0 and b=1, c must be 1, if a=0 and b=0 then c=0, for this purpose i am using the following | operator, which returns the required result, but i am not sure if i am doing it correct or not

<?php 
$a = 0; 
$b = 1;     
$c = $a | $b;
echo("Value in $c = ".$c); 
?>

EDIT: i have gone through the PHP.NET website and find that:

 $a | $b    Or (inclusive or)   Bits that are set in either $a or $b are set.

Reference: http://php.net/manual/en/language.operators.bitwise.php

6
  • 5
    | is bitwise or. you might be looking for || (which is a logical or) Commented Dec 29, 2016 at 16:35
  • but i have just checked the || operator which is not return the required result? Commented Dec 29, 2016 at 16:37
  • Make sure you understand the difference between bitwise (|, &, ...) and logical (&&, ||,...) operators. Commented Dec 29, 2016 at 16:39
  • you are doing it right if you mean bitwise OR. except you don't need the last ?> Commented Dec 29, 2016 at 16:40
  • 2
    In your scenario you really need the bitwise or | and you are doing it right. Commented Dec 29, 2016 at 16:47

1 Answer 1

2

Assuming you only have the states you have in your question, you can use a ternary to do this. It might help others understand what you're doing in the future

$c = ($a || $b) ? 1 : 0;

There's nothing wrong with the way you did it in your question, tho.

Sign up to request clarification or add additional context in comments.

4 Comments

what if $a=1 and $b = 1, then $c will be "0" right?
while i need to get $c = 1 if either is "1" in both the variable "a" and "b"
@Machavity the code you wrote returns the same result like my code? isn't?
@AbdulRahman There's nothing wrong with your way. Mine is just a different way that might be easier to understand. Same result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.