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


while building small feedback-solution people can give number of stars (between 0 , 5), noticed user submitted ratings stored 1 star.

i tried myself submitting 5 stars , backend still shows 1 star.

so looked code , piece causes trouble:

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

actually || operator isn't doing suspected do. in fact returns 1 every time (unless both hand sides $false).

check 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 made paste here: https://eval.in/514978.

what i'm assuming is, php tries convert statements integer (either 0 or 1) depending on given elements, true?

i'm used use || operator in javascript lot can type

var = myfunction() || "default"; 

this check if myfunction() returns bool-ish value , if not uses right hand side value (rather turning int).

|| or operator in php , evaluates either true or false. if want binary or operator should use | instead.

since not equall 0 treated true makes sense of evalations give true, 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 true.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -