Search code examples
phparraysstringarray-filter

2 PHP arrays for merge


How to delete element from array as it has partial in another?

Other words, I need to compare 2 array likely in_array php function, but partially.

Code:

$a = ['abc', 'cde', 'efg', 'hi'];
$b = ['bce', 'ifg', 'hig'];
// return $b without 'hig' because in $a has partially 'hi'

Thanks very much for any solution!


Solution

  • If you want to make any string in $b not have any string in $a as a substring. demo

    <?
    
    $a = ['abc', 'cde', 'efg', 'hi'];
    $b = ['bce', 'ifg', 'hig'];
    
    $b = array_filter($b, function($v) use($a){ 
        foreach($a as $str){
          if(strpos($v, $str) !== false)
            return false;
        }
        return true;
    });
    
    print_r($b);