PHP checks to see if any array value is non-string or numeric?

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

I am currently just checking the strings, so I'm just doing if (array_filter($arr, 'is_string') === $arr)that which seems to work.

+5
source share
7 answers

See: PHP is_string () and is_numeric () .

In combination with, array_filteryou can compare two arrays to make sure 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!');
+8
source

The following will be more effective:

function isStringNumberArray( $array){
  foreach( $array as $val){
    if( !is_string( $val) && !is_numeric( $val)){
      return false;
    }
  }
  return true;
}

This method:

  • will not create a new array
+7

, , . - :

function is_string_or_numeric($var)
{
    return is_string($var) || is_numeric($var);
}

:

if (array_filter($arr, 'is_string_or_numeric') === $arr)
+3

PHP ctype, ctype_alpha() ctype_digit(), :

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

+2

, , " , " ( is_numeric(X), is_int(X) || is_string(X), ). , ( ) :

public function isValid(array $array) {
    $valid = TRUE;

    foreach ($arr as $value) {
        if (!is_int($value) && !is_string($value)) {
            $valid = FALSE;
            break;
        }
    }

    return $valid;
}
0

. , , .

, :

function isNumber($array_element) {
    return is_numeric($array_element);
}

and then call this test function using array_filter

if (array_filter($arr, 'is_number')  {
  // is a number code here.
}

Have you written the function 'is_string ()'? If not, it array_filter($arr, 'is_string')may not work as you think.

0
source

Two facts:

  • foreach is faster than array_map () because it does not call a function at each iteration
  • using === The operator is faster than is_int / is_string, for example:

    if ((int)$value === $value) echo "its an int";

    if ((string)$value === $value) echo "its a string";

0
source

All Articles