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

I want to get another property of an associative array when the first does not 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 PHP, I get 1.

Is there any short way I can do this?

+4
source share
2 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 in 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 it only calculates a boolean value.

+8
source

Try this option:

$arr = array("a" => "123", "b" => "456");
$test = isset($arr['a']) ? $arr['a'] : $arr['b'];
echo $test;

Ternary operator

+2
source

Source: https://habr.com/ru/post/1662512/


All Articles