3v4l.org

run code in 300+ PHP versions simultaneously
<?php function accept_int(int $value) { return $value; } function accept_float(float $value) { return $value; } function accept_string(string $value) { return $value; } function accept_bool(bool $value) { return $value; } $scalarTypes = ['int', 'float', 'string', 'bool']; $data = [ 'int' => 1, 'int-negative' => -1, 'int-zero' => 0, 'float' => 1.2, 'float-negative' => -1.2, 'float-int' => 1.0, 'float-zero' => 0.0, 'string' => 'abc', 'string-empty' => '', 'string-space' => ' ', 'string-int' => '1', 'string-int-negative' => '-1', 'string-int-zero' => '0', 'string-int-spacepad' => ' 1', 'string-int-start' => '1abc', 'string-int-start-spacepad' => ' 1abc', 'string-float' => '1.2', 'string-float-negative' => '-1.2', 'string-float-int' => '1.0', 'string-float-zero' => '0.0', 'string-float-spacepad' => ' 1.2', 'string-float-spacepad-negative' => ' -1.2', 'string-float-start' => '1.2abc', 'string-float-start-negative' => '-1.2abc', 'string-float-start-spacepad' => ' 1.2abc', 'string-float-start-spacepad-negative' => ' -1.2abc', 'bool-true' => true, 'bool-false' => false, ]; function printValue($value) { if (is_string($value)) { return "\"$value\""; } if (is_bool($value)) { return $value ? 'true' : 'false'; } if (is_float($value)) { return number_format($value, 1); } return $value; } $resultsTable = []; foreach ($scalarTypes as $type) { foreach ($data as $key => $value) { $lineKey = $key . ': ' . printValue($value); $acceptFunction = "accept_$type"; try { $deprecatedFlag = false; $noticeFlag = false; set_error_handler(function (int $errno, string $errstr) use (&$deprecatedFlag, &$noticeFlag) { if ($errno === E_NOTICE) { $noticeFlag = true; } else { $deprecatedFlag = true; } echo $errstr . "\n"; }, E_DEPRECATED | E_NOTICE); $result = $acceptFunction($value); set_error_handler(null); if ($result === $value) { $op = 'ok'; } else { $op = 'coerced to ' . printValue($result); if ($deprecatedFlag) { $op .= ' (D)'; } if ($noticeFlag) { $op .= ' (N)'; } } } catch (Throwable $e) { $op = 'error'; } if (!isset($resultsTable[$lineKey])) { $resultsTable[$lineKey] = []; } $resultsTable[$lineKey][$type] = "$op"; } } echo "\n\nResults table:\n\n"; echo ' | ' . str_pad('data type: data', 50, ' ', STR_PAD_LEFT) . ' | '; foreach ($scalarTypes as $type) { echo str_pad($type, 20) . ' | '; } echo "\n"; echo ' | ' . str_pad('', 50, '-') . ' | '; foreach ($scalarTypes as $type) { echo str_pad('', 20, '-') . ' | '; } echo "\n"; foreach ($resultsTable as $key => $results) { echo ' | ' . str_pad($key, 50, ' ', STR_PAD_LEFT) . ' | '; foreach ($results as $type => $result) { echo str_pad($result, 20) . ' | '; } echo "\n"; }

preferences:
26.56 ms | 406 KiB | 5 Q