4

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?

0

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this is exactly what I was looking for :)
Your welcome! I think the second form is a nice improvement of PHP7! :)
note that in PHP the ?? operator is null coalescing, while in JS || is falsy coalescing; so false || 'a' in JS does not translate to false ?? 'a' in PHP (which evaluates to false)
2

Try this variant:

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

Ternary operator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.