Getting the activated PHP extensions list with their versions

Published on 2021-10-07 • Modified on 2021-10-07

In this snippet, we see how to get the activated PHP extensions list with their versions. I use a one-line statement with an arrow function, but the code with a simple loop is more readable.


<?php

declare(strict_types=1);

// src/Controller/Snippet/Snippet168Trait.php

namespace App\Controller\Snippet;

/**
 * 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 Snippet168Trait
{
    public function snippet168(): void
    {
        $extensionsWithVersion = array_combine(get_loaded_extensions(), array_map(static fn (string $extension) => phpversion($extension), get_loaded_extensions()));
        var_dump($extensionsWithVersion);

        // loop version
        $extensionsWithVersion = [];
        foreach (get_loaded_extensions() as $extension) {
            $extensionsWithVersion[$extension] = phpversion($extension);
        }
        var_dump($extensionsWithVersion);

        // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  More on the web

<?php

declare(strict_types=1);

namespace App\Tests\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @covers Snippet168Trait
 */
final class Snippet168Test extends KernelTestCase
{
    /**
     * @covers Snippet168Trait::snippet168
     */
    public function testSnippet168(): void
    {
        $extensionsWithVersion = array_combine(get_loaded_extensions(), array_map(static fn (string $extension) => phpversion($extension), get_loaded_extensions()));

        $extensionsWithVersionLoop = [];
        foreach (get_loaded_extensions() as $extension) {
            $extensionsWithVersionLoop[$extension] = phpversion($extension);
        }

        self::assertSame($extensionsWithVersion, $extensionsWithVersionLoop);
    }
}