Search code examples
phparray-map

using array_map to test values?


Is it possible to use array_map() to test values of an array? I want to make sure that all elements of an array are numeric.

I've tried both

$arrays = array(
         array(0,1,2,3 )
        , array ( 0,1, "a", 5 )
);

foreach ( $arrays as $arr ) {

        if ( array_map("is_numeric", $arr) === FALSE ) {
                echo "FALSE\n";
        } else {
                echo "TRUE\n";
        }
}

and

$arrays = array(
         array(0,1,2,3 )
        , array ( 0,1, "a", 5 )
);

foreach ( $arrays as $arr ) {

        if ( ( array_map("is_numeric", $arr) ) === FALSE ) {
                echo "FALSE\n";
        } else {
                echo "TRUE\n";
        }
}

And for both I get

TRUE
TRUE

Can this be done? If so, what am I doing wrong?

Note: I am aware that I can get my desired functionality from a foreach loop.


Solution

  • array_map returns an array. So it will always be considered 'true'. Now, if you array_search for FALSE, you might be able to get the desire effects.

    From the PHP.net Page

    array_map() returns an array containing all the elements of 
    arr1 after applying the callback function to each one.
    

    This means that currently you have an array that contains true or false for each element. You would need to use array_search(false,$array) to find out if there are any false values.