PHP验证每个数组元素

时间:2015-10-09 08:14:32

标签: php arrays validation

我想要类似的东西 array_validate('is_string',$arr);

如果数组元素都是字符串,那么它将返回TRUE 但是,如果数组中存在/非字符串类型,则返回FALSE。

有没有内置的PHP函数可以做到这一点?

3 个答案:

答案 0 :(得分:1)

使用array_reduce的另一种解决方案:

<form:form

另外,你可以使用其他的callables:

function array_validate($callable, $arr)
{
  return array_reduce($arr, function($memo, $value) use ($callable){ return $memo === true && call_user_func($callable,$value); }, true);
}

array_validate('is_string', ["John", "doe"]); // True
array_validate('is_string', ["John", "Doe", 94]); // false

答案 1 :(得分:0)

运行数组,如果元素不是字符串则返回false。如果所有元素都是字符串,它将到达函数的结尾并返回true。

function array_validate($array){
    foreach($array as $arr){
        if(!is_string($arr){
            return false;
        }
    }
    return true;
}

答案 2 :(得分:0)

没有内置功能,但这可能对您有用:

function array_type_of(array $array, $type)
{
    if ('boolean'  === $type ||
        'integer'  === $type ||
        'double'   === $type ||
        'string'   === $type ||
        'array'    === $type ||
        'resource' === $type ||
        'object'   === $type || // for any object
        'NULL'     === $type) {

        foreach ($array as $v) {
            if (gettype($v) !== $type) {
                return false;
            }
        }
    } else {
        foreach ($array as $v) {
            if (!$v instanceof $type) {
                return false;
            }
        }
    }

    return true;
}

将其用作:

$array = array( /* values */ );

$istype = array_type_of($array, 'boolean');
$istype = array_type_of($array, 'integer');
$istype = array_type_of($array, 'double');
$istype = array_type_of($array, 'string');
$istype = array_type_of($array, 'resource');

$istype = array_type_of($array, 'DateTime');
$istype = array_type_of($array, 'IteratorAggregate');