5

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?

1
  • 3
    its the same concept of ternary in PHP, $var = (condition) ? true: false; Commented Apr 22, 2015 at 10:44

4 Answers 4

13

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;
Sign up to request clarification or add additional context in comments.

Comments

1

It's called ternary operator. In PHP the syntax is almost the same:

$current_user = (is_user_logged_in() ? wp_get_current_user() : null);

1 Comment

Actually it is called a "ternary"..
0

Ofcourse you can do that in php also. Try this -

$current_user = (is_user_logged_in()) ? wp_get_current_user() : null;

Comments

-1
$var = 4; // Initialize the variable
$var_is_greater_than_two = ($var > 2 ? true : false); // Returns true as 4 is greater than 2

May be this helps, its a ternary operator

Comments