php "||" assignment logic compared to Javascript -
i testing heredoc , || functionality
function test() { $obj = [(object)['col1'=>'val1'], (object)['col2'=>'val2'], (object)['col3'=>'val3']]; $output = ''; $mystring = <<<eot non empty string eot; foreach($obj $prop) { foreach($prop $i) { $output .= <<<eot <div style='background-color:lightblue'> \$head : {gettype($i)} </div> eot; } } $out = $output || $mystring || 'couldn\'t find valuable'; echo $out; } test(); i output of
1
which represents boolean true. had output contents of $mystring @ 1 point putting logic in brackets eg
echo ($output || $mystring); and used output:
a non empty string
it stopped working straight after , not sure change broke it.
in javascript:
function test() { var obj = [{'col1':'val1'}, {'col2':'val2'}, {'col3':'val3'}]; var output = ''; var mystring ="a non empty string"; for(var prop in obj) { for(var in prop) { output += "<div style='background-color:lightblue'>" + + " : " + typeof prop[i] + "</div>"; } } out = output || mystring || 'couldn\'t find valuable'; document.write(out); console.log("outputting \n\t" + out); } test(); it different php in terms of logic || during assignment works expected.
0 : string
0 : string
0 : string
for code above. if comment out inner loop so
for(var prop in obj) { /*for(var in prop) { output += "<div style='background-color:lightblue'>" + + " : " + typeof prop[i] + "</div>"; }*/ } i contents of "mystring" is
a non empty string
and if change mystring empty string so
mystring = ""; //"a non empty string"; i
couldn't find valuable
how php's "||" during assignment work ? can explain it?
if assign conditional expression in php boolean (that is, strictly true or false), not work in javascript "truthy" value gets assigned, in php
$a = ""; $b = 42; $c = ($a || $b); // == true while in javascript
var = ""; var b = 42; var c = (a || b); // == 42 and is, sadly, language design.
as @billyonecas reports, in comments docs: http://php.net/manual/en/language.operators.logical.php#77411
to obtain similar behaviour in php, must like:
$a = ""; $b = 42; $c = ($a ?: $b); // newer php version $c = ($a ? $a : $b); // older php version if need concatenate expression, use parethesis:
$c = ($a ? $a : ($b ? $b : "not found"));
Comments
Post a Comment