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.

  • 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` – Rizier123 Aug 16 '15 at 11:05
  • yeah, I get that. But in ruby I can do this and assign value to var based on comparison. –  Aug 16 '15 at 11:06
  • you need to specifically use `empty` function – anurupr Aug 16 '15 at 11:06
  • @anurupr oh really it ain't ruby? its common in many languages –  Aug 16 '15 at 11:07

4 Answers4

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();
Community
  • 1
  • 1
Eloims
  • 5,106
  • 4
  • 25
  • 41
  • awesome. this is what I was looking for :) –  Aug 16 '15 at 11:11
  • 1
    Just to note here: The return value can't be: FALSE, 0, NULL, "" or any other falsely value. – Rizier123 Aug 16 '15 at 11:18
  • @Rizier123 Right, which is exactly equivalent to the non-boolean `||` the OP was familiar with from other languages. – IMSoP Aug 16 '15 at 11:20
  • 1
    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 – ZenithS Jul 18 '17 at 08:31
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: ?:

IMSoP
  • 89,526
  • 13
  • 117
  • 169
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())]
Hasan Tareque
  • 1,761
  • 11
  • 21
0

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

ZenithS
  • 987
  • 8
  • 20