Skip to content

Latest commit

 

History

History
132 lines (108 loc) · 2.69 KB

ManipulateParameters.md

File metadata and controls

132 lines (108 loc) · 2.69 KB

Manipulate parameters

Retrieve all parameters

use function BenTools\QueryString\query_string;

$qs = query_string(
    'foo=bar&baz=bat'
);

print_r($qs->getParams());
/* Array
(
    [foo] => bar
    [baz] => bat
) */

Retrieve specific parameter

print_r($qs->getParam('foo')); // bar

Add / replace parameter

$qs = $qs->withParam('foo', 'foofoo');
print_r($qs->getParams());
/* Array
(
    [foo] => foofoo
    [baz] => bat
) */
print($qs); // foo=foofoo&baz=bat

Remove parameter

$qs = $qs->withoutParam('baz');
print($qs); // foo=foofoo

Create from a complex, nested array

$qs = query_string([
    'yummy' => [
        'fruits' => [
            'strawberries',
            'apples',
            'raspberries',
        ],
    ]
]);

Retrieve a parameter at a specific path

print($qs->getParam('yummy', 'fruits', 2)); // raspberries

Remove a parameter at a specific path

Example: remove "apples", resolved at $params['yummy']['fruits'][1]

$qs = $qs->withoutParam('yummy', 'fruits', 1);
print_r($qs->getParams());
/* Array
(
    [yummy] => Array
        (
            [fruits] => Array
                (
                    [0] => strawberries
                    [1] => raspberries // Yep, this indexed array has been reordered.
                )

        )

)*/

Retrieve key / value pairs

This can be useful if you want to generate hidden input fields based on current query string.

use function BenTools\QueryString\query_string;
use function BenTools\QueryString\withoutNumericIndices;

$qs = query_string(
    'f[status][]=pending&f[status][]=reopened&f[status][]=waiting for changes',
    withoutNumericIndices()
);

foreach ($qs->getPairs() as $key => $value) {
    printf(
        '<input type="hidden" name="%s" value="%s"/>' . PHP_EOL, 
        urldecode($key), 
        htmlentities($value)
    );
}

Output:

<input type="hidden" name="f%5Bstatus%5D%5B%5D" value="pending"/>
<input type="hidden" name="f%5Bstatus%5D%5B%5D" value="reopened"/>
<input type="hidden" name="f%5Bstatus%5D%5B%5D" value="waiting%20for%20changes"/>

More conveniently, you can urldecode keys and values if needed:

foreach ($qs->getPairs($decodeKeys = true, $decodeValues = true) as $key => $value) {
    printf(
        '<input type="hidden" name="%s" value="%s"/>' . PHP_EOL,
        $key,
        $value
    );
}

Output:

<input type="hidden" name="f[status][]" value="pending"/>
<input type="hidden" name="f[status][]" value="reopened"/>
<input type="hidden" name="f[status][]" value="waiting for changes"/>

Previous - Instantiation

Next - Render as string