简体   繁体   中英

Deleting values in an array from another array

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!

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

You're looking for array_diff ie;

$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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM