Extracting the GET parameters of an URL with PHP

Published on 2022-07-06 • Modified on 2022-07-06

This snippet shows how to extract the GET parameters of an URL with PHP. We can use parse_url(), providing the PHP_URL_QUERY as the second parameter, so the query string is directly returned instead of an associative array. Then we can use parse_str(); as you can see, it handles the array parameters perfectly.


<?php

declare(strict_types=1);

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 Snippet209Trait
{
    public function snippet209(): void
    {
        $url = 'https://www.strangebuzz.com/fr/recherche?q=api+assert&first=value&arr[]=foo+bar&arr[]=baz';

        $query = parse_url($url, PHP_URL_QUERY);
        parse_str($query, $queryString);
        /** @var string $q */
        $q = $queryString['q'] ?? '';
        $arr = $queryString['arr'] ?? null;

        echo '$url: '.$url.PHP_EOL;
        echo '$q: '.$q.PHP_EOL;
        echo '$arr: '.var_export($arr, true).PHP_EOL;

        // That's it! 😁
    }
}

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

  Work with me!

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet209Trait
 */
final class Snippet209Test extends KernelTestCase
{
    /**
     * @see Snippet209Trait::snippet209
     */
    public function testSnippet209(): void
    {
        $url = 'https://www.strangebuzz.com/fr/recherche?q=api+assert&first=value&arr[]=foo+bar&arr[]=baz';
        $query = parse_url($url, PHP_URL_QUERY);
        parse_str($query, $queryString);
        self::assertSame('api assert', $queryString['q']);
        self::assertSame(['foo bar', 'baz'], $queryString['arr']);
    }
}