Ternary Operator - can you return from the first clause?

I do not commonly use ternary operators, but when I do, I interpret ternary operators as

(condition) ? (do something if condition is true) : (do something if condition is false).

I’d like to use a ternary operator with a function that either returns a value or returns false as the condition, but I want the value to be returned without running the function again in the (do something if condition is true) spot in the ternary operator.

An example:

function getUserName()
    if (user name is found) {
    return $userName
   return false;

what I would like to do:
$my_return_value = (getUserName()) ?: ‘User name not found’;

what I have to do currently:
$my_return_value = (getUserName()) ? getUserName() : ‘User name not found’;

Is there anyway to achieve what I want here without using the getUserName function twice?

install PHP 5.3+, then the first ternary shorthand is a valid statement.

Thank you. I tried it several more times, it was a problem with my functions themselves, but I thought it was the ternary operator, but your saying it was right made me look in the right place since I assumed it was just a limitation of the ternary operator.

Why not just have GetUserName() return “User name not found” instead of false?

Most likely because the function must be used in other contexts. Having it return the specific string for the situation at hand makes the function less useful elsewhere.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.