Search code examples
phpternary-operatorassignment-operator

PHP: what does a double assignment look like in longform?


I wasn't even sure how to Google this. How would this PHP statement be written longform?

$recentlyViewed = $products = $this->getRecentlyViewedProducts();

Optimizations like this make experts feel smart, and beginners feel really stupid. I'm pretty sure I understand what the outcome is, but maybe I'm wrong.

A: Is this equivalent?

$products = $this->getRecentlyViewedProducts();
$recentlyViewed = ($products) ? true : false;

B: Is this equivalent?

$products = $this->getRecentlyViewedProducts();
$recentlyViewed = $products;

Which is right?

Via Twitter, seems B is equivalent.

Public Service Announcement

Write glaringly simple code. Don't be clever.


Solution

  • $recentlyViewed = $products = $this->getRecentlyViewedProducts();
    

    And

    $products = $this->getRecentlyViewedProducts();
    $recentlyViewed = ($products) ? true : false;
    

    I think this is equivalent:

    Nope its not equivalent.

    Let's see the difference

    $recentlyViewed = $products = range(1,10);
    

    So if you print_r then the value'll be

    print_r($recentlyViewed);
    print_r($products);
    

    This'll print two arrays from [1,2,3,....10] but the

    $products = range(1,10);
    $recentlyViewed = ($products) ? true : false;
    

    So if you print the $products and $recentlyViewed then the result will be the first'll print an array and the other one'll print 1.

    So whats the equivalent of

    $recentlyViewed = $products = $this->getRecentlyViewedProducts();
    

    will be

    $products = $this->getRecentlyViewedProducts();
    $recentlyViewed = $products;
    

    Demo