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

13,435

Solution 1

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!');

Solution 2

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:

  • won't create new array
  • will stop after first invalid value

Solution 3

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)

Solution 4

PHP's ctype functions, specifically ctype_alpha() and ctype_digit() are also worth looking at:

http://php.net/manual/en/book.ctype.php

Share:
13,435
RS7
Author by

RS7

Updated on June 27, 2022

Comments

  • RS7
    RS7 almost 2 years

    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.