Task Four (b) - Input Type Determination - PHP Tutorial
When you enter data into a program, it is always formatted as text.
If necessary, PHP will automatically convert the text input into a numeric
format.
Sometimes it is useful to know in advance what type of data the user entered.
This example tests the input to see if it is numeric. If it is, it then tests
to see if the input was a whole number (integer) or a real number (float). Integers
are whole numbers like 123. Real numbers contain a decimal point like 22.7.
These techniques are used for Input Validation.

Here is the program code.
<?php
set_time_limit(0); // Allow the program an umlimited run time.
// By default programs time out after 30 seconds.
// 0 gives an unlimited run time.
// This time is measured in seconds.
// ===== INPUT ========================================================
echo "\n\nEnter some text or a number or an empty string to quit ... ";
$input = trim(fgets(STDIN));
// ====================================================================
while ($input <> '')
{
if (is_numeric($input))
{
$input = - - $input; // Force conversion of the input to numeric
if (is_int($input))
{
echo "\nYou entered a whole (integer) number.";
}
elseif (is_float($input))
{
echo "\nYou entered a real (floating point) number.";
}
else
{
echo "\nNumeric - Something odd has happened. You should never see this message.";
}
}
elseif(is_string($input))
{
echo "\nYou entered a text string.";
}
else
{
echo "\nString - Something odd has happened. You should never see this message.";
}
// INPUT
echo "\n\nEnter some text or a number or an empty string to quit ... ";
$input = trim(fgets(STDIN));
}
echo "\n\n";
?>
|
Code |
Explanation |
set_time_limit(0); |
Allow the program an umlimited run time. It will be killed after 30
seconds without this line. |
| if (is_numeric($input)) |
Test to see if the input was numeric. |
| $input = - - $input; |
Force the text input into an Integer or Float representation by doing
some arithmetic. The double minus has no effect on $input but this operation
can not be performed on text so PHP converts the input to a numeric type.
Don't confuse -- with - -. The first means subtract one. The second means
negate twice. |
if (is_int($input)) |
Test to see if the input was an Integer (whole number). |
elseif(is_float($input)) |
Test to see if the input was a float (a number including a decimal
point). |
elseif(is_string($input)) |
Thest to see if the input was a string (text). |
Learning Task
Write a program that
- performs addition if you type in two numbers.
- joins the text if you type in two text strings.
- joins the text if you type in one text string and one number (it must treat
the number as text).
|