1

This is my first array

$old = array(
1,2,3,4,5
);

$new(
2,4,5,6
);

I can do by using foreach command and then compare with two arrays. But the problems is I have to separate with which numbers were newly added and which numbers were removed.

And both array can be changed dynamically

Edit:

I have created a function

function get_diff($old,$new){
$small_arr = $large_arr = array();

if( count($old) > count($new) ){
    $small_arr = $new;
    $large_arr = $old;
}else{
    $small_arr = $old;
    $large_arr = $new;
}

$arr = array_diff($large_arr, $small_arr);

return $arr;

}

4 Answers 4

2

Try this :

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Multiple occurrences in $array1 are all treated the same way. This will output :

Array
(
    [1] => blue
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. But i have to find which elements were added, which are removed
1
$old = array(
1,2,3,4,5
);
print_r($old);

$new = array(
2,4,5,6
);
print_r($new);
$removed = array_diff($old, $new);
print_r($removed);

$added = array_diff($new,$old);
print_r($added);

Use array diff basically

1 Comment

Wow... So simple, Working perfectly, Thanks xelbel :)
0

Also check these functions :

http://www.php.net/manual/en/function.array-diff-assoc.php

http://www.php.net/manual/en/function.array-intersect.php

http://www.php.net/manual/en/function.array-intersect-assoc.php

Comments

0
<?php

function get_diff($old,$new){
$small_arr = $large_arr = array();

if( count($old) > count($new) ){
    $small_arr = $new;
    $large_arr = $old;
}else{
    $small_arr = $old;
    $large_arr = $new;
}

    $arr = array_diff($large_arr, $small_arr);
    $values = "New values = ";
    foreach($arr as $arr_values){
        $values.=$arr_values.",";
    }
    $values.="<br/>";
    $same_arr = array_intersect($large_arr,$small_arr);
    $values.= "Earlier values = ";
    foreach($same_arr as $same_values){
        $values.=$same_values.",";
    }
return $values;

}
$old = array(1,2,3,4,5);

$new= array(2,4,5,6);
echo get_diff($old,$new);
?>

DEMO

Comments

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.