-1

this code accepts numbers, e.g. 13.5, 15.6 etc... I need that checked if this is a number only int, e.g. 13, 14 ... etc.

if (is_numeric($r_haslo) == false) {
    $wszystko_ok = false;
    $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!";
}
FSp1333
  • 55
  • 6
  • 1
    Possible duplicate of [How to check whether a variable in $\_GET Array is an integer?](https://stackoverflow.com/questions/12194205/how-to-check-whether-a-variable-in-get-array-is-an-integer) – O.O.Balance Jun 14 '18 at 00:16

3 Answers3

0

if it has to be an integer and integer only this is how I like to do it.

if (is_numeric($r_haslo) == false || ((int)$r_haslo != $r_haslo)) {
    //is an integer
    $wszystko_ok = false;
    $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!";
}

With the updated code above, this now makes sure that $r_haslo is not a number first, and if it is a number, that the number is not an int. So if it's not a number or not an int then it will save the warning to the session.

This way if I send 23 and "23" both are true.
If I send 23 and "23" to is_int() function only 23 will be true.

If you never send string input then is_int() is probably the better way to go.

Update

if (strpos($mystring, ".") || is_numeric($r_haslo) == false || ((int)$r_haslo != $r_haslo)) 
{
    //is an integer
    $wszystko_ok = false;
    $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!";
}

The updated code above will also make sure that there is not a '.' in the input.

Note
if the value is being passed as a number, PHP will automatically convert 12.0 and 12. to 12. if the value is being passed as a string, the srtpos() method will catch it.

Community
  • 1
  • 1
thatguy
  • 1,249
  • 9
  • 26
0

When you say this code accepts, I'll interpret that as you are taking user input by way of a HTTP POST or GET.

The following will only assign and cast to an integer if the posted string contains digits (an unsigned integer within) otherwise it will be assigned null.

<?php
$id = isset($_POST['id']) && ctype_digit($_POST['id'])
    ? (int) $_POST['id']
    : null;
Progrock
  • 7,373
  • 1
  • 19
  • 25
-1

You can us is_int() to check.

if (is_int($r_haslo) == false) {
    $wszystko_ok = false;
    $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!";
}
Joseph_J
  • 3,654
  • 2
  • 13
  • 22