Skip to content

Instantly share code, notes, and snippets.

@frankiejarrett
Last active January 20, 2017 21:36
Show Gist options
  • Select an option

  • Save frankiejarrett/d2d1d60930d2ca4e67d35cf672ac9b13 to your computer and use it in GitHub Desktop.

Select an option

Save frankiejarrett/d2d1d60930d2ca4e67d35cf672ac9b13 to your computer and use it in GitHub Desktop.
Bug in PHP5: ksort() w/ SORT_NUMERIC flag incorrectly sorts PHP_INT_MAX with a bitwise Not operator
<?php
/**
* PHP 5.6.29
*/
var_dump( ~PHP_INT_MAX < -PHP_INT_MAX ); // bool(true)
var_dump( ~PHP_INT_MAX > -PHP_INT_MAX ); // bool(false)
// ksort() with SORT_NUMERIC
$array = [ -PHP_INT_MAX => 'bar', ~PHP_INT_MAX => 'foo', 0 => 'baz' ];
ksort( $array, SORT_NUMERIC );
/*
Array
(
[-9223372036854775807] => bar <------ WRONG!
[-9223372036854775808] => foo
[0] => baz
)
*/
// ksort()
$array = [ -PHP_INT_MAX => 'bar', ~PHP_INT_MAX => 'foo', 0 => 'baz' ];
ksort( $array );
/*
Array
(
[-9223372036854775808] => foo
[-9223372036854775807] => bar
[0] => baz
)
*/
<?php
/**
* PHP 7.0.14
*/
var_dump( ~PHP_INT_MAX < -PHP_INT_MAX ); // bool(true)
var_dump( ~PHP_INT_MAX > -PHP_INT_MAX ); // bool(false)
// ksort() with SORT_NUMERIC
$array = [ -PHP_INT_MAX => 'bar', ~PHP_INT_MAX => 'foo', 0 => 'baz' ];
ksort( $array, SORT_NUMERIC );
/*
Array
(
[-9223372036854775808] => foo
[-9223372036854775807] => bar
[0] => baz
)
*/
// ksort()
$array = [ -PHP_INT_MAX => 'bar', ~PHP_INT_MAX => 'foo', 0 => 'baz' ];
ksort( $array );
/*
Array
(
[-9223372036854775808] => foo
[-9223372036854775807] => bar
[0] => baz
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment