-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!";
}
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I would like it to be false
okay, this is working but i need, that if i press: 12.0 or 12. that this still does not return the true. so how do I block the possibility of entering a dot?
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;

Comments

-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!";
}

1 Comment

is_int() is false for a string even if it contains the characters of an integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.