5

I've been trying to replicate short circuit evaluation in javascript for assignment.

E.g. in Javascript

var myObject = {foo: 'bar'};
// if myObject is undefined then assign an empty array
var obj = myObject || [];

obj will now reference myObject

I tried to replicate this in PHP and found that it just turns it into an expression and returns true or false.

I could do this in PHP like this:

$get = $this->input->get() ? $this->input->get() : array();

The problem with this is I don't know what $this->input->get() is doing behind the scenes so it's not efficient to call the method twice.

So I got creative and found a solution doing it as follows:

// $this->input->get() could return an array or false
$get = ($params = $this->input->get() and $params) ? $params : array();

Problem with this is it may confuse me in the future and it may not be very efficient.

So is there a better way in PHP to assign a variable in a one line expression like this or should I just stick to:

$get = $this->input->get();
if (!$get) {
   $get = array();
}
2
  • Why not have $this->input->get() return an empty query if it doesn't find anything? Commented Dec 19, 2013 at 12:56
  • 1
    @BartFriederichs This method is part of a framework library and overriding it is not really an option. It's just an example anyway to explain my problem. Commented Dec 19, 2013 at 13:02

2 Answers 2

9

Since PHP 5.3, which you are hopefully using as anything else is ancient, there's the ternary ?: operator without the middle part (so, the "binary operator"...?):

$get = $this->input->get() ?: array();
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. I use the ternary operator a lot and just assumed I knew all there was to know about it instead of re-reading the manual. Thanks for lesson.
0

If you want to do it in one line...

$get = ($params = $this->input->get()) ? $params : array();

I don't think it's less efficient in any ways.
You can also do it like...

$get = $this->input->get() ?: array();

But, using this way, I am not sure whether $this->input->get() is called once or twice.

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.