0

This is my code.

$fr = fopen("php://stdin", "r");
$input = fgets($fr);


if (preg_match('/^-?[0-9]{1,4}$/', $input)) {
    echo "Integer.";
} else if (preg_match('/^[-+]?[0-9]*\.?[0-9]+$/', $input)) {
    echo "Float.";
} else if (preg_match('/[a-zA-Z\s]^[0-9]/', $input)) {
    echo "string.";
}

I will get the $input variable from the command line entered. I need to find what datatype the variable is either int, float, string.

Tried gettype() method but it is always string. So only tried with preg_match.

Although in this also i am not getting the correct output.

Ex: 1.2e3 i am getting as string

Parithiban
  • 1,656
  • 11
  • 16

1 Answers1

0

All input from the command line (or any pipe for that matter) will always be a string, since no other types are supported. What you want to figure out is whether your string is numeric and then convert it to a number:

if (is_numeric($input)) {
    $input = +$input;
}

The unary + operator will cause the string to be interpreted as a number and result either in an int or float.

deceze
  • 510,633
  • 85
  • 743
  • 889