Syntax
The syntax of the is_scalar() function in PHP is as follows:
It takes one parameter, which is the $value that represents the variable or value that you want to check if it is of a scalar type.
How to Use is_scalar() Function in PHP
Take a look at some examples in PHP to better understand the use of the is_scalar() function.
Example 1: Outputting a Boolean Value
The following code demonstrates how the is_scalar() function in PHP can be used to determine if the input variable is a Boolean data type or not.
$var = true;
if (is_scalar($var)) {
echo "This variable is a boolean type.";
} else {
echo "This variable is not a boolean type.";
}
?>
In this example, the output will be This variable is a boolean type because the variable var is a Boolean data type.
Example 2: Outputting an Integer Value
The following example determines whether the input variable is of integer type.
$var = 10;
if (is_scalar($var)) {
echo "This variable is an integer type.";
} else {
echo "This variable is not an integer type.";
}
?>
In this example, the output will be This variable is an integer type because the variable var is an integer data type.
Example 3: Outputting a String Value
The following example determines whether the string variable is of string type.
$var = "LinuxHint";
if (is_scalar($var)) {
echo "This variable is a string type.";
} else {
echo "This variable is not a string type.";
}
?>
The above code demonstrates how the is_scalar() function in PHP can be used to determine if the input variable is a string data type or not. In this example, the output will be This variable is a string type because the variable var is a string data type.
Example 4: Outputting a Float Value
The following example determines whether the float variable is of float type.
$var = 4.55;
if (is_scalar($var)) {
echo "This variable is a float type.";
} else {
echo "This variable is not a float type.";
}
?>
Here, the output will be This variable is a float type because the variable var is a float type.
Conclusion
The is_scalar() function in PHP allows checking if the input variable is a scalar type or not. It is useful in determining if the given data type is valid or not. It returns true only if the input variable is a scalar type. It is an important topic for PHP developers and is widely used in PHP programming.