Archive for the ‘PHP’ Category

Recovering HTTP $_GET variables when using Apache’s mod_rewrite

Thursday, May 13th, 2010

Anyone using Apache’s mod_rewrite to handle HTTP requests will know that your $_GET variables  are no longer recognised by the server as the URI is treated as a single string value.

PHP has a function, called mb_parse_str(), that parses the query string representation of an array into a multi-dimensional array. This can be used to correctly represent the query string part of the URL.

The below function returns an array that holds the same values you’d expect from $_GET.

function get_http_vars(){
  $query = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
  mb_parse_str($query, $get);
  return $get;
}

To use the function simply follow the example below;

$get = get_http_vars();

Deep merging two arrays in PHP

Thursday, February 4th, 2010

PHP has a wealth of functions for manipulating arrays, however; I often want to deep merge 2 arrays whilst maintaining the key => value structure. PHP does have functions that will merge multiple arrays but they attempt to maintain duplicate keys.

The below function take 2 arguments (arrays). Arguments are in order of importance, the second arguments values will always overwrite the first arguments values and so on.

function array_merge_replace($base_array, $merge_array){
	$new_array = array();
	$key_list = array_merge((array)$base_array, (array)$merge_array);
	foreach($key_list as $k=>$v){
		if(is_array($base_array[$k])||is_array($merge_array[$k])){
			$new_array[$k] = array_merge_replace($base_array[$k], $merge_array[$k]);
		}else{
			$new_array[$k] = $merge_array[$k] ? $merge_array[$k] : $base_array[$k];
		}
	}
	return $new_array;
}

Removing null values from a PHP Array

Wednesday, July 29th, 2009

The following function will remove all null values from a PHP array. This is especially useful when exploding strings with a post/prefixed delimiter.

function array_remove_null(&$array){
	$new_array = array();
	foreach($array as $k=>$v){
		if($v) $new_array[$k]=$v;
	}
	$array=$new_array;
}

To use the function simply follow the example below;

array_remove_null($your_array_object);

© 2006 - 2010 Matt Lowden. Creative Commons all rights reserved.