I want to delete any element in Array 2 if it contains any of the elements in Array 1. From my research I’ve found that array_filter may be the one to use, but I confused about how I’d do this. I’ll then need to reset the array keys. Could anyone suggest a method?
For example, any element containing ‘123998’ exactly would be removed from Array 2. ‘1239986’ would not be removed.
Array 1
Array ( [0] => 123709 [1] => 123797 [2] => 124089 [3] => 124153 )
Array 2
Array ( [0] => ../fish/cod/123709-sdfgsdfgvsadfg.pdf [1] => ../fish/cod/123797-sdfgsdfg-sdfg-sdfgs-dfg-sd.pdf [2] => ../fish/cod/123998-sdfgsdf-gsdf-gsd-fg-sdfg-.pdf [3] => ../fish/cod/123998-sdfgsdfg-sdf-gsdfg-sdf-g.pdf [4] => ../fish/cod/123998-sdfg.pdf [5] => ../fish/cod/123998-sdfgsdfgsfdg-sdfg.pdf [6] => ../fish/cod/124089-sdfgsdfg-sdfg-sdfg-.pdf [7] => ../fish/cod/124153-sdfgsdfgsdf-gsdfg.pdf )
Advertisement
Answer
Yes, array_filter
sounds good, here is a way to use it :
$pruned_array = array_filter($array2, function($val2) use ($array1) { foreach($array1 as $val1) { if (strpos($val2, val1) !== false) return $val2; } });
If the position of the value to check is always the same (or if it follows the same pattern), it might be more efficient to check this part only instead of using strpos
.