Skip to content

Instantly share code, notes, and snippets.

@macocci7
Created December 10, 2023 01:28
Show Gist options
  • Save macocci7/31fd8c3350306f77d5093239e45b2565 to your computer and use it in GitHub Desktop.
Save macocci7/31fd8c3350306f77d5093239e45b2565 to your computer and use it in GitHub Desktop.
PHP code for verification of limit on number of array elements. (PHPの配列要素数の上限を検証するコード)
<?php
/**
* Code for verification of limit on number of array elements
*/
// initialization
$a = [];
// lower limit of array index
// - lower limit of integer:
// - 32bit-system: - (2 ** 31) === -2147483648
// - 64bit-system: - (2 ** 63) === -9223372036854775808
$a[PHP_INT_MIN] = 'foo';
var_dump($a);
// under limit
// value of $i is to be treated as a float value
// - 64bit-system: float(-9.223372036854776E+18)
$i = PHP_INT_MIN - 1;
var_dump($i);
// this results in overwriting the element of the lowest index,
// because the value of $i is rounded to PHP_INT_MIN.
$a[$i] = 'bar';
var_dump($a);
// upper limit of array index
// - upper limit of integer:
// - 32bit-system: 2 ** 31 - 1 === 2147483647
// - 64bit-system: 2 ** 63 - 1 === 9223372036854775807
$a[PHP_INT_MAX] = 'baz';
var_dump($a);
// over limit
// >> results in "PHP Fatal error"
$a[] = 'qux';
var_dump($a);
@macocci7
Copy link
Author

This code results in:

  • on 64bit-system:
~/work/phptest$ php -f verifyLimitOfArrayElemets.php 
array(1) {
  [-9223372036854775808]=>
  string(3) "foo"
}
float(-9.223372036854776E+18)
array(1) {
  [-9223372036854775808]=>
  string(3) "bar"
}
array(2) {
  [-9223372036854775808]=>
  string(3) "bar"
  [9223372036854775807]=>
  string(3) "baz"
}
PHP Fatal error:  Uncaught Error: Cannot add element to the array as the next element is already occupied in /home/macocci7/work/phptest/verifyLimitOfArrayElemets.php:37
Stack trace:
#0 {main}
  thrown in /home/macocci7/work/phptest/verifyLimitOfArrayElemets.php on line 37

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment