Search code examples
phparrayscomparison

how to compare arrays for additions and subtractions in php?


I have two arrays:

$currentArr = ['apples','oranges','pears'];

$newArr = ['apples','oranges','pears', 'grapes'];

I need to formulate logic that will:

a) check the $newArr against the $currentArr and tell me what was REMOVED and what was ADDED

b) push the removed values onto a new separate array and push the added values onto a new separate array

as I am not extremely well versed in PHP, is this possible? if so, how can I do so?


Solution

  • array_diff() is what you need:

    Returns an array containing all the entries from array1 that are not present in any of the other arrays.

    <?php
    
    $currentArr = ['apples','oranges','pears','test'];
    $newArr = ['apples','oranges','pears', 'grapes'];
    
    $removed = array_diff($currentArr, $newArr);
    print_r($removed);
    // output: 
    // Array ( [3] => test )
    
    // switch the order to get the added items:
    $added = array_diff($newArr, $currentArr);
    print_r($added);
    // output:
    // Array ( [3] => grapes )