Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

comparing two arrays and creating different arrays based on condition

I have this two array

$array1 = Array (
    [0] => 5
    [1] => 25
    [2] => 3
    [3] => 9
    [4] => 15
    [5] => 8
    [6] => 26
    [7] => 1
);

$array2 = Array
(
    [0] => 5
    [1] => 25
    [2] => 3
    [3] => 9
    [4] => 6
    [5] => 26
    [6] => 1
    [7] => 53
    [8] => 22
)

$array1 holds the old value and $array2 holds the new value. i want to create three different arrays out of it.

First : first array should fetch the values that was available in $array1 and not available in $array2 i.e deleted value, here is what i did to get it.

$delete = array_diff($array, $array2);
//Gives me following expected output 
Array
(
    [4] => 15
    [5] => 8
)

Second : second array should fetch the values that was not available in $array1 but got added in $array2 i.e new value, expected output in this case is.

Array (
    [0] => 6
    [0] => 53
    [0] => 22
)

Third : third array should fetch the common values, array values that is available in $array1 and still available in $array2 i.e same or common values. expected output in this case is.

Array (
    [0] => 5
    [1] => 25
    [2] => 3
    [3] => 9
    [4] => 26
    [5] => 1
)

Upvotes: 0

Views: 242

Answers (1)

nickb
nickb

Reputation: 59699

This produces the correct output:

<?php

$array1 = array(
    0 => 5,
    1 => 25,
    2 => 3,
    3 => 9,
    4 => 15,
    5 => 8,
    6 => 26,
    7 => 1
);

$array2 = array(
    0 => 5,
    1 => 25,
    2 => 3,
    3 => 9,
    4 => 6,
    5 => 26,
    6 => 1,
    7 => 53,
    8 => 22
);

$deleted = array_diff( $array1, $array2);
var_dump( $deleted);

$insert = array_diff( $array2, $array1);
var_dump( $insert);

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

http://codepad.org/JianpnYh

Upvotes: 3

Related Questions