#native_company# #native_desc#
#native_cta#

Get differences in Arrays

By Brett Patterson
on December 27, 2005

Version: 1.0

Type: Function

Category: Algorithms

License: GNU General Public License

Description: This function will allow you to get all the differences in multiple arrays (up to 3 arrays).
Inspired by Phence (on the forums), this will return an array filled with all the differences between all the arrays, not just the first.

<?php
/*
Use in this fasion:
$dif = diff_array($array1, $array2 [, $array3]);
The third array is optional.
*/

function diff_array($array1, $array2, $array3=NULL)
{
  $ar3 = (is_array($array3))?TRUE:FALSE;

  foreach($array1 as $a1)
  {
    if(!in_array($a1, $array2))
    {
      $differences[] = $a1;
    }
  }

  foreach($array2 as $a2)
  {
    if(!in_array($a2, $array1))
    {
      if(!in_array($a2, $differences))
      {
        $differences[] = $a2;
      }
    }
  }

  if($ar3)
  {
    $array4 = array_merge_recursive($array1, $array2);
    foreach($array3 as $a3)
    {
      if(!in_array($a3, $array4))
      {
        if(!in_array($a3, $differences))
        {
          $differences[] = $a3;
        }
      }
    }
  }

  return $differences;
}
?>