Search code examples
phpvariablesvariable-assignment

PHP: If statement in variable declaration


I know that in a language like C# you can use an if like statement (I know these have a name but cannot remember what it is called) kind of like this:

var variable = this ? true : false;

(I understand that won't be correct, but it's been a while since I have done them, please correct if wrong).

My question is thus: can you do the same kind of thing in PHP, if so how?

(The site has been built in WordPress but this is a question about generic PHP variable assignment over wp_* functionality)

I want to be able to declare a variable as such :

$current_user = if (is_user_logged_in()) {
    wp_get_current_user();
} else {
    null;
}

and I wondered how I would go about making this a single line variable decloration?


Solution

  • It's called Ternary operator and you can use it in a different set of ways, one way is like so:

     $cake = isset($lie) ? TRUE : FALSE;
    

    The isset(...) can be changed out with any validating / checking operation that you want and the TRUE : FALSE can be replaced with values / variables.

    Another example:

    $cake = ($pieces < 1) ? $cry : $eat;