Documentation for crwlr / query-string (v1.0)

Manipulating Queries


Use this method to set a key value pair:

$query = Query::fromString('foo=1&bar=2')
    ->set('baz', '3');

// string(17) "foo=1&bar=2&baz=3"

Of course the value can also be an array:

$query = Query::fromString('foo=1&bar=2')
    ->set('baz', ['3', '4']);

// string(29) "foo=1&bar=2&baz[0]=3&baz[1]=4"


Append a value to an existing array:

$query = Query::fromString('foo[]=1&foo[]=2')
    ->appendTo('foo', '3');

// string(26) "foo[0]=1&foo[1]=2&foo[2]=3"

Or append a value with a certain key:

$query = Query::fromString('foo[bar]=1&foo[baz]=2')
    ->appendTo('foo', ['quz' => '3']);

// string(32) "foo[bar]=1&foo[baz]=2&foo[quz]=3"


To remove a key from a query there is the remove() method:

$query = Query::fromString('foo[]=1&foo[]=2&bar=3&baz=4')

// string(11) "bar=3&baz=4"


If there is an indexed array with values and you want to remove certain values from it, you can use the removeValueFrom() method.

$query = Query::fromString('foo[]=1&foo[]=2&foo[]=3&foo[]=2')
    ->removeValueFrom('foo', '2');

// string(17) "foo[0]=1&foo[1]=3"


Using the filter() method, you can filter a query, just like with PHP's array_filter() or with laravel collections.

$query = Query::fromString('no1=12&no2=7&no3=23&no4=9&no5=10')
    ->filter(function ($value) {
        return (int) $value >= 10;

// string(20) "no1=12&no3=23&no5=10"

The filter callback also receives the array keys:

$query = Query::fromString('foo=1&bar=2&baz=3&quz=4')
    ->filter(function ($value, $key) {
        return !in_array($key, ['bar', 'quz'], true);

// string(11) "foo=1&baz=3"


And if you want to you can also map query values.

$query = Query::fromString('foo=1&bar=2&baz=3&quz=4')
    ->map(function ($value) {
        return (int) $value + 3;

// string(23) "foo=4&bar=5&baz=6&quz=7"