Cr4xy Cr4xy - 3 months ago 35
Javascript Question

Is there a way to use the or operator in PHP like in JavaScript?

I want to get a other property of a associative array when the first one doesn't exist.


var obj = {"a": "123", "b": "456"};
var test = obj.a || obj.b;

Is it possible to do this in PHP:

$arr = array("a" => "123", "b" => "456");
$test = $arr["a"] || $arr["b"];
echo $test;

When I run the PHP, I get 1.

Is there any short way I could do it?


In PHP you can do

//Check if $arr["a"] exists, and assign if it does, or assign $arr["b"] else
$arr = array("a" => "123", "b" => "456");
$test = isset($arr["a"]) ? $arr["a"] : $arr["b"];

But within PHP 7, you can do

//Does the same as above, but available only from PHP 7
$arr = array("a" => "123", "b" => "456");
$test = $arr["a"] ?? $arr["b"];

See operators

Note that $arr["a"] || $arr["b"] in PHP compute the boolean value only.