Anonym..
Anonym..

Reputation: 333

Php ternary operator to if

I have looked through the PHP manual about ternary operators and I found it hard to understand.

How can I convert this ternary operator to an if statment or edit so it will do the following code below. Instead of echoing I want the code to run a method depending on whether or not the use has logged in,

echo 'User ' . ($openid->validate() ? $openid->identity . ' has ' : 'has not ') . 'logged in.';

Upvotes: 0

Views: 197

Answers (3)

wanovak
wanovak

Reputation: 6127

$value = true;
$value ? runFunction() : (echo "has not logged in");

Extrapolating:

$openid->identity() ? loggedInFunction() : notLoggedInFunction();

Upvotes: 0

Zar
Zar

Reputation: 6892

The direct translation would be:

echo 'User ';

if($openid->validate()) {
   echo $openid->identity . ' has ';
} else {
   echo 'has not '
} 
echo 'logged in.'; 

There are, however, cleaner ways to write code that does the same thing (look at the other answers).

Upvotes: 1

Joe Day
Joe Day

Reputation: 7274

Your code is effectively:

if ($openid->validate()) {
    $temp = $openid->identity . ' has ';
} else {
    $temp = 'has not ';
}

echo 'User ' . $temp . 'logged in.';

It sounds like what you want to do is:

if ($openid->validate()) {
    handleLoggedInFunction();
} else {
    handleNotLoggedInFunction();
}

Upvotes: 1

Related Questions