Let’s say I have an array:
$myArray = array('alfa' => 'apple', 'bravo' => 'banana', 'charlie' => 'cherry', 'delta' => 'danjou pear');
I want to search it for certain keys and if found replace the values of those according to this other array:
$myReplacements = array('bravo' => 'bolognese', 'lie' => 'candy');
I know I can do this:
function array_search_replace($haystack, $replacements, $exactMatch = false) {
foreach($haystack as $haystackKey => $haystackValue) {
foreach($replacements as $replacementKey => $replacementValue) {
if($haystackKey == $replacementKey || (!$exactMatch && strpos($haystackKey, $replacementKey) !== false)) {
$haystack[$haystackKey] = $replacementValue;
}
}
}
return $haystack;
}
But, is there really no smarter/faster way to do it?
EDIT: I also need to be able to search for keyparts, so that ‘lie’ and ‘charlie’ results in a match.
EDIT2: Expected results are:
var_dump(array_search_replace($myArray, $myReplacements));
array(4) { ["alfa"]=> string(5) "apple" ["bravo"]=> string(9) "bolognese" ["charlie"]=> string(5) "candy" ["delta"]=> string(11) "danjou pear" }
var_dump(array_search_replace($myArray, $myReplacements, true));
array(4) { ["alfa"]=> string(5) "apple" ["bravo"]=> string(9) "bolognese" ["charlie"]=> string(6) "cherry" ["delta"]=> string(11) "danjou pear" }
Arrays in PHP are hashes, you don’t need to search for a key, you can access it in O(1) time.
Output: