<?php function absint( $maybeint ): int { if ( ! is_numeric( $maybeint ) ) { return 0; } if ( is_float( $maybeint ) ) { $value = abs( $maybeint ); if ( $value >= PHP_INT_MAX ) { return PHP_INT_MAX; } else { return (int) $value; } } // Convert numeric-string to int. $value = (int) $maybeint; // Special case for the one integer which cannot survive abs(). if ( PHP_INT_MIN === $value ) { return PHP_INT_MAX; } return abs( $value ); } $maybeints = array( 'positive max int times 2' => PHP_INT_MAX * 2, 'zero' => 0, 'string' => 'foo', 'negative 1 int' => -1, 'positive 1 int' => 1, 'negative min int' => PHP_INT_MIN, 'negative min int minus 1' => PHP_INT_MIN - 1, 'negative min int times 2' => PHP_INT_MIN * 2, 'positive max int' => PHP_INT_MAX, 'positive max int plus 1' => PHP_INT_MAX + 1, 'positive max int as string' => (string) PHP_INT_MAX, 'positive max int times 1000 as string' => (string) PHP_INT_MAX . '000', ); foreach ( $maybeints as $case => $maybeint ) { echo "# $case\n\n"; echo 'Input: '; var_dump( $maybeint ); echo 'Output: '; var_dump( absint( $maybeint ) ); echo "\n"; }
You have javascript disabled. You will not be able to edit any code.