3

hah, why does name show value 1?

['name' => ($profile->getNickname() || $profile->getName()),] 

a => b || c if b is empty use c isn't it?

p.s. I know I can do normal if else shorthand (ternary), but its long and unreadable, I don't like it.

4
  • 2
    It is a normal logical OR operator. So if your first function returns FALSE and the second TRUE, then it will evaluate like this: FALSE || TRUE -> TRUE Commented Aug 16, 2015 at 11:05
  • yeah, I get that. But in ruby I can do this and assign value to var based on comparison. Commented Aug 16, 2015 at 11:06
  • you need to specifically use empty function Commented Aug 16, 2015 at 11:06
  • @anurupr oh really it ain't ruby? its common in many languages Commented Aug 16, 2015 at 11:07

4 Answers 4

4

In javascript this is a common thing to write, but PHP will cast to booleans.

This question will answer yours: Best way to give a variable a default value (simulate Perl ||, ||= )

$name = $profile->getNickname() ?: $profile->getName(); 
Sign up to request clarification or add additional context in comments.

4 Comments

awesome. this is what I was looking for :)
Just to note here: The return value can't be: FALSE, 0, NULL, "" or any other falsely value.
@Rizier123 Right, which is exactly equivalent to the non-boolean || the OP was familiar with from other languages.
In PHP 7 you also can use Null Coalescing Operator (??) $name = $profile->getNickname() ?? $profile->getName(); So this will work when the first condition is undefined or falsely without Exception/Error
0

In PHP, the boolean operators || and && always produce a boolean value; the operands are coerced to boolean if necessary, and the original value discarded. This is different from, for example, JavaScript, where the operands are evaluated for "truthiness" but their original values retained.

The 1 you see is just because you echoed a boolean, which in turn coerces the true to a string 1.

PHP does have a shorthand operator for what you want, though: ?:

Comments

0

($profile->getNickname() || $profile->getName()) is just a condition which comes true (1) that's why its showing 1.

it should be as follows:

// if nick name is set and not empty then show it otherwise show name [ 'name' => ((isset($profile->getNickname()) && ($profile->getNickname() != "")) ? $profile->getNickname() : $profile->getName())] 

1 Comment

how would you like maintaining that kind of code? :)
0

return the boolean value from function if isset(data)
$profile->getNickname() and
$profile->getName()
to decision a condition.

Comments