PHP check if any array value is not a string or numeric?

RS7 picture RS7 · Feb 6, 2012 · Viewed 13.1k times · Source

I have an array of values and I'd like to check that all values are either string or numeric. What is the most efficient way to do this?

Currently I'm just checking for strings so I was just doing if (array_filter($arr, 'is_string') === $arr) which seems to be working.

Answer

Jeff Lambert picture Jeff Lambert · Feb 6, 2012

See: PHP's is_string() and is_numeric() functions.

Combined with array_filter, you can then compare the two arrays to see if they are equal.

function isStringOrNumeric($in) {
// Return true if $in is either a string or numeric
   return is_string($in) || is_numeric($in);
}

class Test{}

$a = array( 'one', 2, 'three', new Test());
$b = array_filter($a, 'isStringOrNumeric');

if($b === $a)
    echo('Success!');
else
    echo('Fail!');