PHP对每个数组元素的验证函数


PHP validate function on each array element

我想要 array_validate('is_string',$arr);

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

是否有任何内置的PHP函数可以做到这一点?

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

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

也可以使用其他可调用对象:

array_validate([$object, "method"], ["something"]);
array_validate("is_array", [ [], [] ]); // true

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

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

没有内置函数,但这可能适合您:

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