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

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

PDF Print E-mail

Question: How to remove values in one array from another array using PHP?

 

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

 

Answer: 

  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:

    <?php
    
        $arrayA = array('one','two');
        $arrayB = array('one','two','three','four','five');
        
        $newArray = array_diff($arrayB,$arrayA);
        
        echo '<pre>';
        print_r($newArray);
        echo '</pre>';
    
    ?>
    
  3. The code example above will print the following:
    Array
    (
        [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





+/-
+/- Write comment
Your Contact Details:
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
Security Please input the anti-spam code that you can read in the image.
 

Go Daddy $7.49 .com Sale!