Reputation: 1405
I have
$Array1 = [3=>'dog', 7=>'cat', 9=>'duck', 10=>'dog', 11=>'dog'];
$Array2 = ['cat'=>'sofa', 'dog'=>'kennel', 'duck'=>'pond'];
I want the output $ArrayOut where
$ArrayOut = [3=>'kennel', 7=>'sofa', 9=>'pond', 10=>'kennel', 11=>'kennel'];
I can do this easily through a foreach
loop
foreach ($Array1 as $key => $value) {
$ArrayOut[$key] = $Array2[$value];
}
but I was thinking if I could avoid a loop and use a combination of inbuilt PHP array functions to create the same output.
Any clue would be helpful thanks.
Upvotes: 2
Views: 459
Reputation: 809
Try this:
$Array1 = [3=>'dog', 7=>'cat', 9=>'duck'];
$Array2 = ['cat'=>'sofa', 'dog'=>'kennel', 'duck'=>'pond'];
# Flip the array
$new = array_flip($Array1);
# Replace the values
$new2 = array_replace($Array2, $new);
# This step you would lose the duplicates
$n = array_combine(array_merge($new2, $new), $Array2);
print_r($n);
Ouptut:
Array
(
[7] => sofa
[3] => kennel
[9] => pond
)
Upvotes: -1
Reputation: 47863
There isn't (currently) a native function for this exact task. Using array_map()
will require a user-function to be used. One benefit of functional-style iteration is that it reduces the number of global variables. Otherwise use a classic loop and modify the input array's values by reference. If any given value is not represented as key in the lookup array, then the null coalescing operator will just use the original value in the assignment. This avoids Notices without making any iterated function calls.
Code: (Demo)
$array = [3 => 'dog', 7 => 'cat', 9 => 'duck', 10 => 'dog', 11 => 'dog'];
$lookup = ['cat' => 'sofa', 'dog' => 'kennel', 'duck' => 'pond'];
foreach ($array as &$value) {
$value = $lookup[$value] ?? $value;
}
var_export($array);
Code >=PHP7.4: (Demo)
var_export(
array_map(fn($v) => $lookup[$v] ?? $v, $array)
);
Both Output:
array (
3 => 'kennel',
7 => 'sofa',
9 => 'pond',
10 => 'kennel',
11 => 'kennel',
)
Upvotes: 1
Reputation: 360
I think this does the trick.
$Array1 = [3=>'dog', 7=>'cat', 9=>'duck', 10=>'dog', 11=>'dog'];
$Array2 = ['cat'=>'sofa', 'dog'=>'kennel', 'duck'=>'pond'];
$ArrayOut = array_map(function($v) use($Array2){
return $Array2[$v];
}, $Array1);
print_r($ArrayOut);
//Array ( [3] => kennel [7] => sofa [9] => pond [10] => kennel [11] => kennel )
Upvotes: 4
Reputation: 2129
Edit: I have missread the purpose. Your best bet would be to work a foreach array in my opinion.
I'll still leave my answer here for future reference, if someone requires matching values from one array to keys of another array
There is something you can use, as long as your arrays are in the order you want.
http://php.net/manual/en/function.array-combine.php
array_keys will extract into an array, the keys of a specified array
array_values will extract into an array, the values of specified array
array_combine will, as the function says, combine into an array the match arguments - being the first array argument the keys and the second the values.
Upvotes: -1