I want something like
array_validate('is_string',$arr);
If the array elements are all strings, then it will return TRUE.
But, if there is/are non-string type in the array, it will return FALSE.
Is there any built-in PHP function that does this?
I want something like
array_validate('is_string',$arr);
If the array elements are all strings, then it will return TRUE.
But, if there is/are non-string type in the array, it will return FALSE.
Is there any built-in PHP function that does this?
Another solution using 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
Also, you could use other callables:
array_validate([$object, "method"], ["something"]);
array_validate("is_array", [ [], [] ]); // true
Run through array, if a element is not a string return false. If all elements are string it will reach the end off the function and return true.
function array_validate($array){
foreach($array as $arr){
if(!is_string($arr){
return false;
}
}
return true;
}
There is no built in function, but this might work for you:
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;
}
Use it as:
$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');