2

I have 2 arrays and I would like to delete everything in the first array that is in the second array. In thise case I would like to delete "ibomber" and "apphero" in array one. I tried something with unset, but it doesn't look like it works.

array (size=5)
  0 => string 'Air Hippo' (length=9)
  1 => string 'iBomber Defense Pacific' (length=23)
  3 => string 'AppHero' (length=7)
  5 => string 'Pillboxie' (length=9)
  6 => string 'Monogram' (length=8)

array (size=2)
  0 => string ' iBomber Defense Pacific' (length=24)
  1 => string ' AppHero' (length=8)

This is what I tried:

foreach ($_SESSION["appsarray"] as $k=>$v)
{
    foreach ($_SESSION["finalapps"] as $k2=>$v2)
    {
        if ($v == $v2)
        {   
            unset ($_SESSION["appsarray"][$k]);
        }
    }
}

Session appsarray is my first array and session finalapps is my second array.

Thanks!

3
  • $array1 = array_diff($array1,$array2); Commented Dec 18, 2012 at 18:19
  • Someone told me to trim the values of my second array because they were not the same lenght. It worked, but he deleted his answer.. Commented Dec 18, 2012 at 18:22
  • For the sake of correctness, I fixed my answer to do this in one pass with a minimal amount code. I also added case insensitivity, which could also be of interest. Commented Dec 18, 2012 at 18:36

2 Answers 2

3
function TrimmedStrCaseCmp($str1,$str2)
{
    return strcasecmp(trim(str1),trim(str2));
}

$result = array_udiff(values,to_remove_from_values,'TrimmedStrCaseCmp');

http://php.net/manual/en/function.array-udiff.php

Sign up to request clarification or add additional context in comments.

Comments

2

You're looking for array_diff i.e.;

$appsarray = array('Air Hippo','iBomber Defense Pacific','AppHero','Pillboxie','Monogram');
$finalapps = array('iBomber Defense Pacific','AppHero');
$result = array_diff($appsarray,$finalapps);

print_r($result);

Will output;

Array ( [0] => Air Hippo [3] => Pillboxie [4] => Monogram )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.