php - Logical operators should be avoided (use || instead of 'or') sensiolabs insight


I'm using SensioLabs Insight to keep my projects code quality on top of the used tool's best practices.

This line cause warning during SLInsight analysis:

$handle = fopen($file, 'w') or die('Cannot open file: '.$file);

SensioLabs say :

Logical operators should be avoided.


The or operator does not have the same precedence as ||. This could lead to unexpected behavior, use || instead.

Ok but, if I simply use || instead of 'or' , like this :

$handle = fopen($file, 'w') || die('Cannot open file: '.$file);

I get the classicNo such file or directory erro because offopen fail, instead of what I'm expecting (die action and return message).

To avoid this, I use a condition before do thefopen:

if(!file_exists($file)) {
    throw $this->createNotFoundException('Le fichier '.$file.' n\'existe pas.');
$handle = fopen($file'.log', 'r');

What is the good use of '||' in a variable assignment for what I want ?

Thank's by advance for enlighten me.




Logical operators should be avoided.

In your case is the precedence of theor that you want. I think that SensioLabs refers to a complex expressions in a condition, which can be misleading.

or operator have lower precedence, even lower than assignment= operator. Example:

if ($a = getRecordOrFalse($userId) || $boolValue) {

is as you would expect:

if (($a = getRecordOrFalse($userId)) || ($boolValue)) {

$a contains the value returnedgetRecordOrFalse, and this condition istrue if$boolValue is true, even if$a isn't. But with theor you get a completely different behavior:

if ($a = getRecordOrFalse($userId) or $boolValue) {

that's equivalent to:

if ($a = (getRecordOrFalse($userId) or $boolValue)) {

Now$a would be a boolean value given by the result ofgetRecordOrFalse($userId) or $boolValue)'s condition.

But in your case this make sense:

$handle = (fopen($file, 'w') or die('Cannot open file: '.$file));

What you can do to improve readability is to use a condition like this:

if (false === $handle = fopen($file, 'w')) {
    die('Cannot open file: '.$file);

Or simply

if (!$handle = fopen($file, 'w')) {
    die('Cannot open file: '.$file);

People are also looking for solutions to the problem: php - Diplaying a javascript map (amChart) in a Ghost post


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.