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
)
[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
}
Mail this!
- Comments (0)
- PingBacks (0)
- TrackBacks (0)


» Latest comments