Verification: a143cc29221c9be0

Php build url from array

Arguments

First Argument ($url)
The base URL. The parameters will be added to this.
Second Argument ($params)
An associative array containing all the parameters and their values.
Third Argument ($use_existing_arguments)
This is an optional argument. If this is set to 'true', the function will use the parameters that are present in the current page along with the $params array when creating the URL.

Example Code

Two Arguments

getLink("http://www.google.com/search",array(
		"q"=>"binny",
		"hello"=>"world",
		"results"=>10)
	);

will return
http://www.google.com/search?q=binny&hello=world&results=10

Three Arguments

Assume that the current page is http://www.example.com/index.php?sort_order=name&page=3

getLink("http://www.example.com/edit.php",array(
		"item_id"	=> 15,
		"return_url"=> 'index.php'
	),
true);

This call will return
http://www.example.com/edit.php?sort_order=name&page=3&item_id=15&return_url=index.php

Extract the query string with parse_url

In this example we’ll look at the URL from querying [chris hope] at Google (I don’t show up until the second page, by the way) which looks like this:

http://www.google.com/search?hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=

Using parse_url we can easily extract the query string like so:

$parts = parse_url($url);
echo $parts['query'];

The output from the above will be this:

hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=

As an aside, before continuing with using parse_str to extract the individual parts of the query string, doing print_r($parts) would show this:

Array
(
    [scheme] => http
    [host] => www.google.com
    [path] => /search
    [query] => hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=
)

Extract the query string parts with parse_str

The parse_str function takes one or two parameters (the second from PHP 4.0.3) and does not return any values. If the second parameter is present, the values from the query string are returned in that parameter as an associative array. If it is not present, they are instead set as variables in the current scope, which is not really ideal.

So, without the first parameter:

parse_str($parts['query']);

You could now echo the "q" value like this:

echo $q;

In my opionion, it’s better to have the values returned as an array like so:

parse_str($parts['query'], $query);

Now doing print_r($query) would output this:

Array
(
    [hl] => en
    [source] => hp
    [q] => chris hope
    [btnG] => Google Search
    [meta] =>
    [aq] => f
    [oq] =>
)

The "q" value could now be echoed like this:

echo $query['q'];