Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 731
RS7 Avatar asked Feb 06 '12 21:02

RS7


People also ask

How do you check if a value is an integer or string in PHP?

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.

How do you check if a value exists in an array PHP?

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 check array is associative or not in PHP?

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.

Is not a number in PHP?

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.


1 Answers

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!');
like image 120
Jeff Lambert Avatar answered Nov 14 '22 23:11

Jeff Lambert