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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With