Replace array keys

Views: 37 Last modified: September 17th, 2011 Comments: 0

This snippet will replace array keys with specified replacements. Personally i don’t encourage this as you define keys for a reason, and why replace them ? And what about the value’s ?

However, i saw lots of people searching for this kind of snippet, so here is one. This snippet takes 2 arguments.

Parameters

  • array The array to iterate over
  • array (index)keys to replace => (element)replace with

Example of use:

$search = array('Language' => 'PHP' , 500 => 100, 'Java' => 'Jquery');
$replace = array(500 => 250, 'Language' => 'This is it!');
print_r(array_replace_keys($search, $replace));

This will output:

Array (
[This is it!] => PHP
[250] => 100
[Java] => Jquery
)

The function

function array_replace_keys($search, $replace)
{
	if (!is_array($search) || !is_array($replace)) return false;
	$flipped = array_flip($search); // Flip array

	foreach ($replace as $key => $value) // For each the replace array
	{
		$found = array_search($key, $flipped);
		if ($found !== false) $flipped[$found] = $value;
	}
	return array_flip($flipped); // Flip it back and return
}
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

    Mail this!

    To: From:Sum {0+7} =  
    Anything to add ?

        You must be logged in to post a comment.