Hello,
since there are currently no type declarations for specific arrays (int[], string[], MyClass[], etc.), I'd like to ask if it would make sense to have a function array_get_type() in php core?
As I'm not a C developer, I can only ask for your help for the implementation. I think having it in the core will provide much better performance, esp. when the result could get cached on first evaluation (and the cache is invalidated when the array is modified).
function array_get_type(array $array): string
{
$result = null;
foreach ($array as $elem) {
$type = get_debug_type($elem);
$result ??= $type;
if ($type != $result) {
return 'mixed';
}
}
return $result ?? '';
}
echo array_get_type([1,2,3]), PHP_EOL; // int
echo array_get_type([0.1, 0.2]), PHP_EOL; // float
echo array_get_type(['a','b']), PHP_EOL; // string
echo array_get_type([true,false]), PHP_EOL; // bool
echo array_get_type([null,null]), PHP_EOL; // null
echo array_get_type([]), PHP_EOL; // ''
echo array_get_type([new stdClass, new stdClass]), PHP_EOL; // 'stdClass'
echo array_get_type(['a',null]), PHP_EOL; // mixed
echo array_get_type([1,0.2]), PHP_EOL; // mixed
echo array_get_type([new class {},new class {}]), PHP_EOL; // class@anonymous
echo array_get_type([function() {},function() {}]), PHP_EOL; // Closure
echo array_get_type([new DateTime(), new DateTime()]), PHP_EOL; // DateTime
echo array_get_type([new DateTime(), new DateTimeImmutable()]), PHP_EOL; // mixed
Having this function would make it easier to check types of arrays and avoid things like array_sum([1, 'a', 'b', 2]);
Best Regards
Thomas