To filter an array for particular elements use the array_filter()
function. The function takes 2 arguments: an array and a callback function¹. The callback function is applied to all array elements and only those elements for which the callback function evaluates to true are returned. You can use either a named function
function myfilter($v) {
return !((strlen($v) < 15) || (strpos($v, 'red') !== false));
}
$result = array_filter($array, 'myfilter');
or an anonymous function (AKA lambda expression)
$callback = function($v) {
return !((strlen($v) < 15) || (strpos($v, 'red') !== false));
}
$result = array_filter($array, $callback);
Both approaches will return the result
Array
(
[2] => Kleenex Used By Dr. Dre
)
Use the function array_values()
on the result if you want a new zero-based array instead of an array where the keys are the indexes from the original array:
$result = array_values(array_filter($array, $callback));
Result:
Array
(
[0] => Kleenex Used By Dr. Dre
)
¹ Actually, array_filter()
takes 3 arguments: array, callback function, and mode. The third parameter (mode) is optional and controls whether the callback function is applied to values and/or keys of the array. The default is to apply it to values only, which is what you want in your scenario, hence you need to provide only the first 2 parameters.