tags:

views:

79

answers:

4

Hi all.

Is there any simple way of checking if all elements of an array are instances of a specific type without looping all elements? Or at least an easy way to get all elements of type X from an array.

Thank you.

Regards, Diogo

+1  A: 

Is there any simple way of checking if all elements of an array [something something something] without looping all elements?

No. You can't check all the elements of an array without checking all the elements of the array.

Though you can use array_walk to save yourself writing the boilerplate yourself.

Anon.
+2  A: 

You cannot achieve this without checking all the array elements, but you can use built-in array functions to help you.

You can use array_filter to return an array. You need to supply your own callback function as the second argument to check for a specific type. This will check if the numbers of the array are even.

function even($var){
  return(!($var & 1));
}

// assuming $yourArr is an array containing integers.
$newArray = array_filter($yourArr, "even");
// will return an array with only even integers.

As per VolkerK's comment, as of PHP 5.3+ you can also pass in an anonymous function as your second argument. This is the equivalent as to the example above.

$newArray = array_filter($yourArr, function($x) { return 0===$x%2; } );
Anthony Forloney
With php 5.3+ you can also use anonymous functions `$newArray = array_filter($yourArr, function($x) { return 0===$x%2; } );`
VolkerK
A: 

You can also combine array_walk with create_function and use an anonymous function to filter the array. Something alon the lines of:

$filtered_array = array_filter($array, create_function('$e', 'return is_int($e)'))
belgarat
Need to use single quotes, or escape the $ with a backslash.
chris
+1  A: 
$s = array("abd","10","10.1");
$s = array_map( gettype , $s);
$t = array_unique($s) ;
if ( count($t) == 1 && $t[0]=="string" ){
    print "ok\n";
}
ghostdog74
I actually used the filter solution since my requirements changed by this answer is great! That actually completely answer the initial question and is really useful for validation.Thanks.
DiogoNeves