I imagine you can never beat O(n)
as all the elements need to be checked that they conform to the rule. The below checks each element once O(n)
and removes it, if it is not an integer then does a simple comparison.
Still will have a slightly larger storage complexity however (needs to store the filtered array).
O(n)
is a representation of complexity, in this case the complexity is n
(the number of elements in the array) as each element must be looked at once.
If for example you wanted to multiple every number by every other number the complexity is approximately O(n^2)
as for each element you must look at each other element (though this is a poor example)
See this guide for further information on Big O Notation as it is called
However try the below (adapted from previous question)
if($only_integers === array_filter($only_integers, 'is_int')); // true
if($letters === array_filter($letters, 'is_int')); // false
You could then do
/**
* Test array against provided filter
* testFilter(array(1, 2, 'a'), 'is_int'); -> false
*/
function testFilter($array, $test) {
return array_filter($array, $test) === $array;
}