How to remove values in one array from another array using PHP

Written by Ian Carnaghan · 30 sec read >

Example: I have array with values and another array B. I need to remove the values in array from the values in array B.


  1. Use the PHP function array_diff

    • Description

      • array array_diff ( array $array1 , array $array2 [, array $ … ] )
      • Compares array1  against array2  and returns the difference.
    • Parameters
      • array1 = The array to compare from
      • array2 = An array to compare against
  2. Code example below:

        $arrayA = array('one','two');
        $arrayB = array('one','two','three','four','five');
        $newArray = array_diff($arrayB,$arrayA);
        echo '<pre>';
        echo '</pre>';
  3. The code example above will print the following:
        [2] => three
        [3] => four
        [4] => five
  4. Explanation:
    • Array A values will be removed from array B
    • The $newArray variable will contain the values of array B with values from array A removed

Last Updated On March 22, 2018
Written by Ian Carnaghan
I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment. Profile

Leave a Reply

Notify of