DEV Community

Cover image for 5 tips in PHP 🐘
Saymon Tavares
Saymon Tavares

Posted on Edited on

5 tips in PHP 🐘

In this article, I’ll show you 10 tips that can improve your PHP code πŸ” 🐘
In order to make this article easier to read, I’ll write some pieces of code that I’ve encountered and introduce a commented solution if needed, as you know there are 4242424242424 ways to do the same thing ✨ and It’s OK to disagree with my solution πŸ˜…

πŸ‘€ For my examples I use PHP 7.4
🏁 πŸ”₯

1 - In this use case, just return the expression πŸ‘Œ

if($foo === 42) {
    return true;
}
return false;

// can be
return $foo === 42;
Enter fullscreen mode Exit fullscreen mode

2 - Null coalescing operator for the win 😍

if($foo !== null) {
    return $foo;
}
return $bar;

// can be
return $foo ?? $bar;
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ It’s very handy to avoid exceptions when you want to access a key that doesn’t exist

3 - Straight to the point πŸ₯…

$this->user = ['firstname' => 'smaine', 'mail' => 'contact@smaine.me'];

return $this->user;

// can be
return $this->user = ['firstname' => 'smaine', 'mail' => 'contact@smaine.me'];
Enter fullscreen mode Exit fullscreen mode

4 - Initialize your helper once πŸ˜›

class FooTransformer
{
    private $propertyAccessor;

    public function transform(array $data): Foo
    {
        $accessor = $this->getAccessor();
        // stuff
    }

    private function getAccessor(): PropertyAccess
    {
        return $this->propertyAccessor ??= PropertyAccess::createPropertyAccessor(); // @lito 
    }
}
Enter fullscreen mode Exit fullscreen mode

5 - Unpack an array 🎩

$users = [
    ['smaone', 'php'],
    ['baptounet', 'javascript'],
];

foreach($users as [$username, $language]) {
    // $username contains the 1st key "smaone" for the 1st iteration
    // $language contains the 2nd key "php" for the 1st iteration
}
Enter fullscreen mode Exit fullscreen mode

In the same way, we can also assign variables from an array, it is useful if a function returns an array πŸš€

function getFullname(int $id): array
{
    $statement = $pdo->prepare("SELECT id, lastname, firstname FROM user WHERE id = ?");
    $statement->execute([$id]);
    $result = $statement->fetch();

    // suppose $result contains [42, 'luke', 'lucky'];
    return $result;
}

// main.php 
[$id, $lastname, $firstname] = getFullname(42);
// $id contains 42
// $lastname contains luke
// $firstname contains lucky
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the read!

Feel free to follow me on GitHub, LinkedIn and DEV for more!

Top comments (4)

Collapse
 
lito profile image
Lito •
    private function getAccessor(): PropertyAccess
    {
        return $this->propertyAccessor ?? $this->propertyAccessor = PropertyAccess::createPropertyAccessor(); 
    }
Enter fullscreen mode Exit fullscreen mode

Is same as:

    private function getAccessor(): PropertyAccess
    {
        return $this->propertyAccessor ??= PropertyAccess::createPropertyAccessor(); 
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nfcristea profile image
Florin Cristea • • Edited

??= will also assign the value on first call, besides checking if it's set, meaning that the second time it gets reached it will have a value assigned and PropertyAccess::createPropertyAccessor() will no longer get called.
?? is just a classic isset check meaning the call to createProperyAccesor() is made every time it gets reached.
They're quite different although they look similar.

Collapse
 
saymon profile image
Saymon Tavares •

thanks guy!

Collapse
 
bdelespierre profile image
Benjamin Delespierre •

Here's another one for you: extract variables from string using patterns

$str = "123:456";

preg_match('/(\d+):(\d+)/', $str, $matches);

list(, $a, $b) = $matches + [null, null, null];

var_dump($a, $b); // 123, 456
Enter fullscreen mode Exit fullscreen mode