Reputation: 2361
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.
Upvotes: 5
Views: 15177
Reputation: 2363
Two facts:
using the === Operator is faster than is_int / is_string, like so:
if ((int)$value === $value) echo "its an int";
if ((string)$value === $value) echo "its a string";
Upvotes: 0
Reputation: 24661
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!');
Upvotes: 8
Reputation: 946
Lots of answers for this one. If you want to use the method you've been using, you will want to write your own function for this.
so for each element in the array you are going to check if it is a number:
function isNumber($array_element) {
return is_numeric($array_element);
}
and then call that test function using array_filter
if (array_filter($arr, 'is_number') {
// is a number code here.
}
Have you written a function 'is_string()'? If not, array_filter($arr, 'is_string')
may not be working the way you think it is.).
Upvotes: 0
Reputation: 21007
More effective would be this:
function isStringNumberArray( $array){
foreach( $array as $val){
if( !is_string( $val) && !is_numeric( $val)){
return false;
}
}
return true;
}
This method:
Upvotes: 7
Reputation: 28929
Well, it really depends on what you mean by "either string or numeric" (this could mean is_numeric(X)
, or is_int(X) || is_string(X)
, or any number of other things). Probably the most efficient way (though it's more verbose) is this:
public function isValid(array $array) {
$valid = TRUE;
foreach ($arr as $value) {
if (!is_int($value) && !is_string($value)) {
$valid = FALSE;
break;
}
}
return $valid;
}
Upvotes: 0
Reputation: 10302
If you're looking to do a single run through the array, you could write your own function to check each of the values against your specific criteria. Something like:
function is_string_or_numeric($var)
{
return is_string($var) || is_numeric($var);
}
Then you can filter your array like:
if (array_filter($arr, 'is_string_or_numeric') === $arr)
Upvotes: 3
Reputation: 14136
PHP's ctype functions, specifically ctype_alpha()
and ctype_digit()
are also worth looking at:
http://php.net/manual/en/book.ctype.php
Upvotes: 2