user3600400
user3600400

Reputation: 181

PHP compare 2 arrays and update values of one array

I currently have two arrays:

$array1 = array("Option 1", "Option 2", "Option 3", "Option 4");
$array2 = array("Option 2", "Option 3", "Option 8");

I want to see which values in $array2 can be found in $array1. If there is a value in $array2 which can be found in $array1 (eg. Option 2), I want to change the value of that item to something different (eg. Confirmed). In addition, I want to preserve the order of the items in $array2.

Upvotes: 1

Views: 1454

Answers (3)

hlscalon
hlscalon

Reputation: 7552

You can use array_map function, mapping all the values to see which correspond in $array1 and return the message you want, or return the regular values:

$array2 = array_map(function($a) use ($array1) {
    if (in_array($a, $array1)){
        return "confirmed";
    }
    return $a;
}, $array2);

print_r($array2);

Output:

Array
(
    [0] => confirmed
    [1] => confirmed
    [2] => Option 8
)

Upvotes: 1

pecci
pecci

Reputation: 540

You can use the array_intersect.

A clearer example of the key preservation of this function:

<?php

$array1 = array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);

var_dump(array_intersect($array1, $array2));
var_dump(array_intersect($array2, $array1));

?>

result:

array(3) {
  [0]=> int(2)
  [1]=> int(4)
  [2]=> int(6)
}

array(3) {
  [1]=> int(2)
  [3]=> int(4)
  [5]=> int(6)
}

This makes it important to remember which way round you passed the arrays to the function.

You can see more at: http://php.net/manual/en/function.array-intersect.php

Upvotes: 1

FuzzyTree
FuzzyTree

Reputation: 32402

foreach($array2 as &$value) {
    if(in_array($value,$array1)) {
        $value = 'Confirmed';
    }
}

Upvotes: 3

Related Questions