0

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?

3
  • iterate over all entries in $arr, check if the current entry exists within $data if yes replace, otherwise go on Commented Jun 21, 2017 at 8:23
  • What's your expected result? Commented Jun 21, 2017 at 8:33
  • $arr should search in $data if there is a match $arr should replace value with $data i'e 5782,5783 etc Commented Jun 21, 2017 at 8:34

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

Iterate $files array and check if value is in $data

foreach ($files as &$file) {
   if (isset($data[$file])) {
       $file = $data[$file];
   }
}

2 Comments

thanks for your help, but it does not give me any output, just blank screen
Do you do var_dump($files);?
0

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.

1 Comment

try the given example in the doc. If u have trouble understanding it, explain your doubts and i ll be happy to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.