note 129473 added to ref.array
| From: | et2225zas14@susu.ru | Date: | Wed, 08 May 2024 11:32:16 +0000 |
| Subject: | note 129473 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221318@lists.php.net to get a copy of this message | ||
Be careful with type hints in callbacks when using array-traverse functions. In some cases, this may
silently cause the data type of elements to change.
<?php
declare(strict_types=1);
// Missing fatal TypeError, No side effects
$unexpected = array_filter(['123', (string) PHP_INT_MAX], fn (int $item) => true);
var_dump($unexpected);
// Missing fatal TypeError, Typecasting side effect
$unexpectedTypecasting = array_map(fn (int $item) => $item, ['123', (string)
PHP_INT_MAX]);
var_dump($unexpectedTypecasting);
// Missing fatal TypeError, Typecasting side effect
$unexpectedTypecasting = array_map(fn (string $item) => $item, [123, PHP_INT_MAX]);
var_dump($unexpectedTypecasting);
// Missing fatal TypeError, Typecasting side effect
$unexpectedTypecasting = array_reduce(['123', (string) PHP_INT_MAX], fn (?int $carry, int
$item) => $item);
var_dump($unexpectedTypecasting);
$bigIntValue = bcadd((string) PHP_INT_MAX, '1');
// Fatal TypeError
$expectedTypeError = array_map(fn (int $item) => $item, [$bigIntValue]);
var_dump($expectedTypeError);
?>
The above example will output (PHP version 8.3.6, error_reporting E_ALL):
<?php
array(2) {
[0]=>
string(3) "123"
[1]=>
string(19) "9223372036854775807"
}
array(2) {
[0]=>
int(123)
[1]=>
int(9223372036854775807)
}
array(2) {
[0]=>
string(3) "123"
[1]=>
string(19) "9223372036854775807"
}
int(9223372036854775807)
Fatal error: Uncaught TypeError: {closure}(): Argument #1 ($item) must be of type int, string given
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.131 (proxied: 185.5.48.152)
----
Manual Page -- https://php.net/manual/en/ref.array.php
Edit -- https://main.php.net/note/edit/129473
Del: integrated -- https://main.php.net/note/delete/129473/integrated
Del: useless -- https://main.php.net/note/delete/129473/useless
Del: bad code -- https://main.php.net/note/delete/129473/bad+code
Del: spam -- https://main.php.net/note/delete/129473/spam
Del: non-english -- https://main.php.net/note/delete/129473/non-english
Del: in docs -- https://main.php.net/note/delete/129473/in+docs
Del: other reasons-- https://main.php.net/note/delete/129473
Reject -- https://main.php.net/note/reject/129473
Search -- https://main.php.net/manage/user-notes.php