We help IT Professionals succeed at work.

OR and || not having the same effect! What's wrong???

dsrnu used Ask the Experts™
I have the following code... and the output is as follows:

if i use OR i get

if i use || i get

the results should be the same shouldn't it? im using php 4
$offset = ( ! $this->form_validation->is_natural_no_zero($ext_offset) || ! in_array($ext_offset, $valid_offset_values) ? 'INVALID' : 'VALID');

$offset = ( ! $this->form_validation->is_natural_no_zero($ext_offset) OR ! in_array($ext_offset, $valid_offset_values) ? 'INVALID' : 'VALID');

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
They are not the same.  || has higher precidence over Or.  Also, logical outcomes can be different.

See http://www.php.net/manual/en/language.operators.logical.php
In equations, it is best to use ||.


im actually using php 5.. but i dont think it has to do with precedence.. is this a bug in php 5???
you example like this:
// same as (($e = false) or true),
// expression is true but $e is assigned to false
$e = false or true;
php  interpreter now understand:
(($e = false) or true);
$e = false;
expression value true;
Try grouping your elements with parenthesis, see if that makes a difference:

$offset = ( ((! $this->form_validation->is_natural_no_zero($ext_offset)) || (! in_array($ext_offset, $valid_offset_values))) ? 'INVALID' : 'VALID');

$offset = ( ((! $this->form_validation->is_natural_no_zero($ext_offset)) OR (! in_array($ext_offset, $valid_offset_values))) ? 'INVALID' : 'VALID');


i get this:

echo phpversion(); // returns 5.3.5
echo ( ! TRUE || ! FALSE ? 'VALID' : 'INVALID'); // returns VALID
echo ( ! TRUE OR ! FALSE ? 'VALID' : 'INVALID'); // return 1

why the difference?
As I say, try grouping with parenthesis.

The problem is that you are using the negation operator (!) which could cause PHP to interpret in various ways.


echo ( ((! TRUE) || (! FALSE)) ? 'VALID' : 'INVALID');
echo ( ((! TRUE) OR (! FALSE)) ? 'VALID' : 'INVALID');

Did you read this in the link I gave you?

Another example that might help.

(isset($panelemail) && !empty($panelemail) ? $panelemail : $userdata['email']);
returns the userdata email address, but this

(isset($panelemail) AND !empty($panelemail) ? $panelemail : $userdata['email']);
returns false.

The reason is that the two types of ands have a different order of precedence.  "&&" is higher than "AND", and the "?:" operator just happens to come between the two.  Also, since "||" (or) is actually higher than "AND," you should never mix &&s and ||s with ANDs and ORs without paretheses.

It is a mistake to think that operator precidence was done away with in PHP 5.