How to check a string for an integer? Not using regulars and the ctype_digit function. There should be no letters, points, etc. in the line.

  • is there an integer or is the string integer? - IVsevolod
  • Is the string an integer. Without exponent 1e4,1.4 and so on. Only numbers. - Alexander Chernozhukov
  • Simple regulars are not as slow as they scare. But you can stupidly in the forehead. function containsOnlyDigits ($ str) {for ($ i = 0; $ i <strlen ($ str); $ i ++) {if (intval ($ str [$ i]) == 0 && $ str [$ i]! = = '0') {return false; }} return true; } - etki
  • one
    @Etki, this is exactly the case when /^\d+$/ is quite appropriate :) But it’s better to send incomprehensible restrictions (do not use regulars, don’t wear a blue-buttoned shirt, etc.) in the forest. - user6550
  • @Alexander Chernozhukov, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Deleted

2 answers 2

Removed options with is_numeric () and is_int () from the answer - they do not give the desired result *

Type coercion and strict validation:

 if((integer)$foo === $foo || (string)((integer)$foo) === $foo) 
  • Not suitable. The string for the presence of an integer. Without any characters, only numbers and that's it. - Alexander Chernozhukov
  • I propose instead of strpos to simply wrap the variable in trim () before checking it - dekameron
  • @Denis Khvorostin, stumble on this: is_numeric ('1e10') - VenZell

The first thing that came to mind:

 <?php $cases = array('1234567890', '1e10', '1.5'); $allowed_chars = range('0 ', '9 '); for ($i = 0; $i < count($cases); ++$i) { $is_there_bad_symbols = false; $current_case = $cases[$i]; for ($j = 0; $j < strlen($cases[$i]); ++$j) { $char = $current_case[$j]; if (!in_array($char, $allowed_chars, true)) { $is_there_bad_symbols = true; break; } } if ($is_there_bad_symbols) { echo $current_case . ' - test failed' . PHP_EOL; } else { echo $current_case . ' - test passed' . PHP_EOL; } } 

 1234567890 - test passed 1e10 - test failed 1.5 - test failed 

Or short:

 <?php $allowed_chars = range('0 ', '9 '); for ($i = 0; $i < strlen($string); ++$i) { $char = $string[$i]; if (!in_array($char, $allowed_chars, true)) { $is_there_bad_symbols = true; break; } } echo $is_there_bad_symbols ? 'test failed' : 'test passed';