Reputation: 1875
I've just started learning PHP, i'm trying to get a numeric input by using fopen. The program should just ask user to type a number, and echo if the number is odd, even, or not a number. The thing is, no matter what I type, it is never considered as a number. Here's my code
#!/usr/bin/php
<?php
echo "Entrez un nombre: ";
$handle = fopen ("php://stdin","r");
$nbr = fgets($handle);
if (is_numeric($nbr))
{
if ($nbr % 2 == 0)
echo "Le chiffre $nbr est Pair\n";
else if ($nbr % 2 == 1)
echo "Le chiffre $nbr est Impair\n";
}
else
echo "'$nbr' n'est pas un chiffre\n";
?>
At this point, I can type anything I want as an input, but the answer is always "'[what I typed] ' n'est pas un chiffre"
Upvotes: 2
Views: 344
Reputation: 9445
fgets
gets a line from the stream, including the trailing newline character. $nbr
is thus "123\n"
, which is not numeric.
You can check this by printing strlen($nbr)
(is 2
) and then ord($nbr[1])
which prints 10
- the ASCII code for the newline character.
Use trim($nbr)
to remove the newline character, and also additional whitespace before and after the input.
Upvotes: 2