Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 963
Pascal Raszyk Avatar asked Jul 11 '26 14:07

Pascal Raszyk


1 Answers

|| 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.

like image 193
Bas van Stein Avatar answered Jul 14 '26 08:07

Bas van Stein