Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference between ? : and ||

Tags:

php

What difference is there between using the ?: conditional operator and the || Logical OR.

I am finding that my code works with:

$screenpixelratio = !empty($_COOKIE['screenpixelratio']) || $_COOKIE['screenpixelratio'] || $fallback_pixelratio;

But not:

$screenpixelratio = !empty($_COOKIE['screenpixelratio']) ? $_COOKIE['screenpixelratio'] : $fallback_pixelratio;

Could someone please explain why it would work with one, but not the other.

like image 276
ccdavies Avatar asked Feb 15 '13 15:02

ccdavies


People also ask

What is || used for?

We use the symbol || to denote the OR operator. This operator will only return false when both conditions are false. This means that if both conditions are true, we would get true returned, and if one of both conditions is true, we would also get a value of true returned to us. Let's go over a few examples.

What is difference between and || in C?

The | operator evaluates both operands even if the left-hand operand evaluates to true, so that the operation result is true regardless of the value of the right-hand operand. The conditional logical OR operator ||, also known as the "short−circuiting" logical OR operator, computes the logical OR of its operands.

Is || and && the same?

&& is used to perform and operation means if anyone of the expression/condition evaluates to false whole thing is false. || is used to perform or operation if anyone of the expression/condition evaluates to true whole thing becomes true. so it continues till the end to check atleast one condition to become true.

What does || mean in code?

The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool . Logical OR has left-to-right associativity.


2 Answers

The first (conditional or) is saying...

this or this or this

The other (ternary operation) is saying

if this then this otherwise that
like image 162
Grant Thomas Avatar answered Sep 26 '22 08:09

Grant Thomas


|| Binary operators are operators that deal with two arguments

as its says it will check first if its true than not gonna check further else check further

?: ternary operator is an operator that takes three arguments. The arguments and result can be of different types.

Expression1 ? Expression2 : Expression3;

enter image description here

like image 43
NullPoiиteя Avatar answered Sep 24 '22 08:09

NullPoiиteя