Reputation: 253
I have the following arrays:
$files = ['376840000000367020', '376840000000375036', '376840000000389001'];
$arr = [];
foreach ($files as $key => $name) {
$arr[] = $name;
}
$data = [
'376840000000367020' => '5782',
'376840000000375036' => '5783',
'376840000000389001' => '5784',
];
print_r($arr);
This returns:
Array ( [0] => 376840000000367020 [1] => 376840000000375036.... )
I want to compare 2 arrays $arr
and $data
if the $key
is found in $arr
replace value with the $data
, I'm trying get following output:
Array ( [0] => 5782 [1] => 5783 .... )
I have lots of data to compare so its not ideal to iterate over $arr
inside foreach.
How would i go about doing this?
Upvotes: 0
Views: 80
Reputation: 3354
You can use array_key_exists
function to check a key exists in array:
<?php
$files = ['376840000000367020','376840000000375036','376840000000389001'];
$data = array(
'376840000000367020' => '5782',
'376840000000375036' => '5783',
'376840000000389001' => '5784',
);
$arr = [];
foreach($files as $key=>$name){
if(array_key_exists($name, $data)) {
$arr[] = $data[$name];
}
}
print_r($arr);
Upvotes: 1
Reputation: 6255
Use array_map passing a callback that checks if the value exist in the 2nd array and return it's value in that case, or the item otherwise.
Upvotes: 0
Reputation: 43451
Iterate $files
array and check if value is in $data
foreach ($files as &$file) {
if (isset($data[$file])) {
$file = $data[$file];
}
}
Upvotes: 0