Using the PHP compact function with the Symfony debug functions

Published on 2022-06-30 • Modified on 2022-06-30

This snippet shows how to use the PHP compact function with the Symfony debug functions. Symfony dump() and dd() functions are great to debug. They allow passing an arbitrary number of variables. That's cool, but if you have too many variables, it can be not very clear, and you have to return to the original call to see the exact order. We can use the compact() function to see each variable's name and its associated value.



namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;

 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
trait Snippet208Trait
    public function snippet208(Request $request): void
        $clientIp = $request->getClientIp();
        $locale = $request->getLocale();
        dump($clientIp, $locale);
        dump(compact('clientIp', 'locale'));

        // in dev mode, the debug is added in the profiler. It looks like this:
        $output = <<<OUTPUT
Snippet208Trait.php line 19

Snippet208Trait.php line 19

Snippet208Trait.php line 20

array:2 [▼
  "clientIp" => ""
  "locale" => "en"

        echo $output;

        // That's it! 😁

 Run this snippet   Read the doc  Random snippet

  Work with me!