0

I am reading another person's code and here I saw something that I do not understand how to interpret it:

$this->mobile && $content['mobile'] = $this->mobile;

I have always seen && used as a logical operator between boolean expressions and on the right side of the assignment symbol. This seems pretty confusing to me and I couldn't find what it means on php.net.

stressed out
  • 522
  • 6
  • 24
  • Does this answer your question? ['AND' vs '&&' as operator](https://stackoverflow.com/questions/2803321/and-vs-as-operator) – Haridarshan Jun 14 '21 at 11:37
  • IMHO it's bad coding style, they are using it as a shortened `if` - so the value is only set if `$this->mobile` is *true*. – Nigel Ren Jun 14 '21 at 11:40
  • @NigelRen Oh, I see. So, if ``$this->mobile`` is set, the other expression (the assignment) after the logical operator is executed but if the first expression is not set, the assignment is ignored. Am I right? – stressed out Jun 14 '21 at 11:42
  • Main thing is try it out (be careful what with *not being set* means) – Nigel Ren Jun 14 '21 at 11:42

1 Answers1

0
$this->mobile && $content['mobile'] = $this->mobile;

means exactly the same thing as

$this->mobile && ($content['mobile'] = $this->mobile);

Remember that in PHP, assignments are also expressions (they return values), and remember that && evaluates the second expression only if there's a need for it, and in case of false first argument, there's no need, because the whole expression is false.

Being a developer myself, I can deduce that the initial intention of the author was to create a shorthand, for an if statement:

if ($this->mobile) $content['mobile'] = $this->mobile;

which does the same thing.

Danon
  • 2,771
  • 27
  • 37