I have an array with some values
Array ( [0] => MSC-00107.mp4 [1] => SPTWLL-00108.mp4 [2] => FSHNWLL-00109.mp4)
So I want to remove elements contains a part of string
$remove = 'WLL';
So if an element contains the string set in $remove I want remove from array If I use in_array it will remove only if the string is equal
if (in_array($remove, $array))
{
unset($array[array_search($remove,$array)]);
}
and it doesn't work. Can you help me? thanks
CodePudding user response:
You can filter array, fiddle:
$array = array_filter($array, function($value) use ($remove) {
return false === strpos($value, $remove);
});
CodePudding user response:
You could return elements that don't match:
$array = preg_grep("/$remove/i", $array, PREG_GREP_INVERT);
CodePudding user response:
My example just loops through all the elements of the array removing the items containing a given string:
$array = ['test', 'test123', '456test', 'anotherone'];
removeItemsFromArrayMatching($array, 'test');
var_dump($array);
function removeItemsFromArrayMatching(&$array, $remove){
$i = 0;
foreach($array as &$item)
{
if( str_contains($item, $remove) )
unset($array[$i]);
$i ;
}
$array = array_values($array);
}
CodePudding user response:
You can use strpos() which will show you whether to string contains another phrase or not. You need to use it with foreach
foreach($array as $key){
if (strpos( $key, $remove ) !== FALSE ){
unset($array[array_search($remove,$array)]);
}
}