In this post, you're going to learn about extracting key/value params from a URL string (which is different from getting the query string as key/value pairs from the current page's URL).
Extract Query String Part From a URL String
To extract the query string part from a string URL you can simply use the parse_url()
function, for example, like so:
$url = 'https://designcise.com/?key1=value1&key2=value2'; echo parse_url($url, PHP_URL_QUERY); // output: 'key1=value1&key2=value2'
Create an Array of Query Params From String URL
To get the query string params as an array you can use the parse_str()
function after extracting the query string part from the URL string. For example:
$url = 'https://designcise.com/?key1=value1&key2=value2'; $queryStr = parse_url($url, PHP_URL_QUERY); parse_str($queryStr, $queryParams); echo var_dump($queryParams); // output: [ 'key1' => 'value1', 'key2' => 'value2' ]
This would also correctly parse duplicate key names followed by square brackets (for example, ?key[]=value1&key[]=value2
) into a numerically indexed child array belonging to that key. For example:
$url = 'https://designcise.com/?key[]=value1&key[]=value2'; $queryStr = parse_url($url, PHP_URL_QUERY); parse_str($queryStr, $queryParams); echo var_dump($queryParams); // output: [ 'key' => ['value1', 'value2'] ]
Similarly, if the squared brackets had some text between them, they would be correctly parsed into an associative array belonging to the parent key. For example:
$url = 'https://designcise.com/?key[foo]=value1&key[bar]=value2'; $queryStr = parse_url($url, PHP_URL_QUERY); parse_str($queryStr, $queryParams); echo var_dump($queryParams); // output: [ 'key' => ['foo' => 'value1', 'bar' => 'value2'] ]
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.