Share your favourite PHP trick!
Bert Heyman

Bert Heyman @bertheyman

About: Laravel enthousiast, likes reading dev stories and the openness of communities like dev.to

Location:
Belgium
Joined:
Nov 6, 2017

Share your favourite PHP trick!

Publish Date: Oct 20 '19
5 3

What simple trick or feature do you really like to use?

Comments 3 total

  • Bert Heyman
    Bert HeymanOct 20, 2019

    Personally, I'm a big fan of the ?? syntax (available from PHP 7 and up).

    An example:

    <?php
    
    // Long syntax
    !empty($book->author->name) ? $book->author->name : 'no known author'
    
    // Short syntax with the coalescing operator
    $book->author->name ?? 'no known author'
    
    // Chaining ?? can tidy up your views (arbitrary example here)
    Hello, <?= $user->nickname ?? $user->name ?? 'stranger' ?>
    
    Enter fullscreen mode Exit fullscreen mode
  • Aschwin Wesselius
    Aschwin WesseliusOct 21, 2019

    Well, even though it's not really about PHP, it's still a nice trick. Let's A/B test some code!

    <?php
    
    /*/
    $a = 1 + 1;
    /*/
    $a = 2 + 2;
    /**/
    echo $a . "\n";
    

    This will print case no. 2.

    If you put another asterisk (*) in the first little comment block, see what happens!

    <?php
    
    /**/
    $a = 1 + 1;
    /*/
    $a = 2 + 2;
    /**/
    echo $a . "\n";
    

    Suddenly, this will print case no. 1!

    By just putting/removing one asterisk it will toggle both cases.

    I bet this will work in multiple languages. However, I didn't test it anywhere but PHP.

    • Bert Heyman
      Bert HeymanOct 22, 2019

      A little known trick that's really nice when testing out some code. Just gave it a go and worked like a charm - thanks!

Add comment