Re: how to update array keys and keep element order ?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 21 May 2010 10:56,  <cr.vegelin@xxxxxxxxx> wrote:
> How do I update an array key without disturbing the element order ?
> Suppose an existing array("FR", values ...)
> where I want to change 0 => "FR" to "country" => "FR"
> and keep the original element order.
>
> TIA, Cor
>

Something like ...

function arrayKeyChange(array &$array, $oldKey, $newKey) {
	if (!array_key_exists($oldKey, $array)) {
		trigger_error('Requested key does not exist.', E_USER_WARNING);
		return False;
	}
	if (array_key_exists($oldKey, $array) && array_key_exists($newKey, $array)) {
		trigger_error('Will result in duplicate keys.', E_USER_WARNING);
		return False;
	}

	// Split keys/values
	$keys = array_keys($array);
	$values = array_values($array);
	
	// Find position of oldKey
	$oldKeyPos = array_search($oldKey, $keys, True);
	
	// Replace key
	$keys[$oldKeyPos] = $newKey;
	
	// Combine keys/values
	$array = array_combine($keys, $values);

	return True;
}


-- 
-----
Richard Quadling
"Standing on the shoulders of some very clever giants!"
EE : http://www.experts-exchange.com/M_248814.html
EE4Free : http://www.experts-exchange.com/becomeAnExpert.jsp
Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498&r=213474731
ZOPA : http://uk.zopa.com/member/RQuadling

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux