praszyk February 2016

PHP: Logical Operator: Why does (5 || 3) return 1?

While building a small Feedback-Solution where people can give a number of stars (between 0 and 5), I noticed that all user submitted ratings are stored with just 1 star.

I tried it myself by submitting 5 stars and the backend still shows 1 star.

So I looked into the code and this is the piece that causes the trouble:

$feedback->rating = ($wire->input->post->rating || 1);

Actually the || operator isn't doing what I suspected it to do. In fact it just returns 1 every time (unless both hand sides are $false).

Check my example code below:

$example1 = ($true || 5);
$example2 = ($false || 5);
$example3 = ($false || $false);
$example4 = (5 || 0);
echo $example1."\n";
echo $example2."\n";
echo $example3."\n";
echo $example4."\n";

Also I made a paste here: https://eval.in/514978.

What I'm assuming is, PHP tries to convert the statements to an integer (either 0 or 1) depending on the given elements, is that true?

I'm used to use the || operator in JavaScript a lot where I can just type

var i = myFunction() || "default";

This will check if myFunction() returns a bool-ish value and if not just uses the right hand side value (rather than turning everything into an int).

Answers


Bas van Stein February 2016

|| is the or operator in PHP and it evaluates to either true or false. If you want the binary or operator you should use | instead.

Since everything not equall zero is treated like true it makes sense that all of the evalations give true, which as integer becomes 1.

You can see more info here: http://php.net/manual/en/language.operators.logical.php

Example ----- Name -----Result
$a || $b ------- Or ---------TRUE if either $a or $b is TRUE.


Hanky Panky February 2016

$feedback->rating = ($wire->input->post->rating || 1);

Come on, It is returning TRUE which you see as 1

Try this

echo TRUE;    //1

What you are looking for is a ternary operator.

$feedback->rating = $wire->input->post->rating ?: 1;
                                               ^^

This gives you that value if it is set, otherwise gives you an actual 1.


AltWouss February 2016

There is a difference to PHP || handling as opposed to other languages.

In PHP 5 || 7 will always return true; the || operator will always return a boolean.

5 || 7 = true;

In other languages like javascript. 5 || 7 will return 5 and 7 || 1 will return 7; the || operator will return the parameter that was evaluated true (or the last parameter);

5 || 7 = 5;
7 || 1 = 7;
0 || 7 || 1 = 7;
0 || 0 = 0;

In PHP you can achieve the same by using a ternary operator:

$result = $int ? $int : 1;

if the $int is implicitly true, $result will be $int, otherwise $result will be 1;

Or since PHP 5.3:

$result = $int ?: 1;

Post Status

Asked in February 2016
Viewed 2,146 times
Voted 6
Answered 3 times

Search




Leave an answer