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.
The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
How to check if PHP array is associative or sequential? There is no inbuilt method in PHP to know the type of array. If the sequential array contains n elements then their index lies between 0 to (n-1). So find the array key value and check if it exist in 0 to (n-1) then it is sequential otherwise associative array.
The is_nan() function checks whether a value is 'not a number'. This function returns true (1) if the specified value is 'not-a-number', otherwise it returns false/nothing.
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!');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With