Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

JavaScript:

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

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?

like image 349
Cr4xy Avatar asked Dec 24 '22 23:12

Cr4xy


1 Answers

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.

like image 86
AnthonyB Avatar answered Dec 26 '22 17:12

AnthonyB