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?

jeromegamez
  • 3,348
  • 1
  • 23
  • 36
Can O' Spam
  • 2,718
  • 4
  • 19
  • 45

4 Answers4

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;
Epodax
  • 1,828
  • 4
  • 27
  • 32
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);
Said Kholov
  • 2,436
  • 1
  • 15
  • 22
0

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

$current_user = (is_user_logged_in()) ? wp_get_current_user() : null;
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
-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

Can O' Spam
  • 2,718
  • 4
  • 19
  • 45
Rajendra Gupta
  • 381
  • 1
  • 16