Working with the Query String Component
Getting The Query as an Array
If you're after the query of a url you may want to get it as an array. Don't worry, nothing easier than that:
$url = Url::parse('https://www.example.com/foo?bar=baz&key=value');
var_dump($url->queryArray());
Output
array(2) {
["bar"]=>
string(3) "baz"
["key"]=>
string(5) "value"
}
And the same method can be used to set the whole query string from an array:
$url = Url::parse('https://www.example.com/foo');
$url->queryArray(['param' => 'value', 'yo' => 'lo', 'crwlr' => 'url']);
var_dump($url->__toString());
Output
string(55) "https://www.example.com/foo?param=value&yo=lo&crwlr=url"
Advanced Query String API
If you're already on PHP 8 you can additionally install the crwlr / query-string package for a more advanced API to access and manipulate the query string.
composer require crwlr/query-string
After the package is installed the queryString()
method returns an instance of the Query
class from that package. You can find the docs for this class here.
A quick example:
$url = Url::parse('https://www.example.com/listing?page[number]=3&page[size]=25');
$url->queryString()
->get('page')
->set('number', '4');
var_dump($url->__toString());
// string(68) "https://www.example.com/listing?page%5Bnumber%5D=4&page%5Bsize%5D=25"