PHP add variable to URL

This function inserts a variable to an URL string and will return the new string/url adjusting the "?" or "&" character properly:

Example

add_var_to_url("total_items", 10, "http://example.com?sort_by=price");

will return:

http://example.com?sort_by=price&total_items=10

It will also replace variable if needed:

add_var_to_url("total_items", 10, "http://example.com?total_items=5&sort_by=price");

will return:

http://example.com?sort_by=price&total_items=10

The complete function is

<?php
if(!function_exists("add_var_to_url")){
	function add_var_to_url($variable_name,$variable_value,$url_string){
		// first we will remove the var (if it exists)
		// test if url has variables (contains "?")
		if(strpos($url_string,"?")!==false){
			$start_pos = strpos($url_string,"?");
			$url_vars_strings = substr($url_string,$start_pos+1);
			$names_and_values = explode("&",$url_vars_strings);
			$url_string = substr($url_string,0,$start_pos);
			foreach($names_and_values as $value){
				list($var_name,$var_value)=explode("=",$value);
				if($var_name != $variable_name){
					if(strpos($url_string,"?")===false){
						$url_string.= "?";
					} else {
						$url_string.= "&";
					}
					$url_string.= $var_name."=".$var_value;
				}
			}
		} 
		// add variable name and variable value
		if(strpos($url_string,"?")===false){
			$url_string .= "?".$variable_name."=".$variable_value;
		} else {
			$url_string .= "&".$variable_name."=".$variable_value;
		}
		return $url_string;
	}
}?>

The oposite function (remove variable from url) is also available.

Download the files

Download the function PHP file (1KB)


Share with Google Plus