0

This is a standalone expression in a function:

$var OR $var = $var

What does this expression exactly do?

Never saw this before and can't find the answer as I have no idea how is this called.

Code itself is from: Сodeigniter Template on Github

public function build($view, $data = array(), $return = FALSE)
{
    // Set whatever values are given. These will be available to all view files
    is_array($data) OR $data = (array) $data;
    // Merge in what we already have with the specific data
    $this->_data = array_merge($this->_data, $data);

...
5
  • I'd say that it does nothing relevant... can we see the function? Commented May 28, 2016 at 21:48
  • Is $var supposed to be in the code 3 times? Commented May 28, 2016 at 21:49
  • 1
    Assignment (=) has higher precedence than OR, so it sets a variable value to itself, and then ors it with itself again, and then does absolutely nothing.... it's basically a waste of processing cycles as it stands Commented May 28, 2016 at 21:51
  • is_array($data) OR $data = (array) $data; doesn't do the same thing of $var OR $var = $var. Why didn't you post that from the start? Commented May 28, 2016 at 21:58
  • 1
    it's equivalent to if (!is_array($data)) { $data = (array) $data; } Commented May 28, 2016 at 22:00

1 Answer 1

3

Given an expression like yours

is_array($data) OR $data = (array) $data;

we check the precedence table on http://php.net/operators.precedence first. There we see = is above OR. Thus the line is equal to this:

is_array($data) OR ($data = (array) $data);

Next we have to check the table for associativity. or is left associative so it checks is_array($data). If that returns true the orexpression as a whole returns trueand nothing else happens.

If is_array($data) returns false we have to evaluate further, so $data = (array) $data is executed.

In the end this is a "smart" way to write

if (!is_array($data)) {
    $data = (array) $data;
}

Actually in this specific case we could also write only

$data = (array) $data;

As the (array) cast is a no-op if $data already is an array.

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

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.