What is PHP is_scalar() Function?
If you want to know whether a variable is a scalar or not, use is_scalar() function.
What is a scalar value?
A scalar value is a single, simple value. It indicates a single piece of data. Examples of PHP scalar value are-
- Boolean
- Integer
- Float
- String
What is a non-scalar value?
A non-scalar value is a multi value which holds multiple values. Examples of PHP non-scalar value are-
- Array
- Object
- Resource
- NULL
Syntax:
is_scalar(variable)
Parameters:
The Function has 1 parameter which is required-
variable (Required): It specifies a variable.
Return Values:
The function returns-
- TRUE, if the variable is scalar.
- FALSE, if the variable is not scalar.
Examples:
Example 1:
<?php
echo "Is PHP a scalar value? " . (is_scalar("PHP") ? 'Yes' : 'No') . "<br />";
echo "Is 100 a scalar value? " . (is_scalar(100) ? 'Yes' : 'No') . "<br />";
echo "Is 1.5 a scalar value? " . (is_scalar(1.5) ? 'Yes' : 'No') . "<br />";
echo "Is FALSE a scalar value? " . (is_scalar(FALSE) ? 'Yes' : 'No') . "<br />";
echo "Is [1,2] a scalar value? " . (is_scalar([1, 2]) ? 'Yes' : 'No') . "<br />";
echo "Is NULL a scalar value? " . (is_scalar(NULL) ? 'Yes' : 'No');
?>
Output:
Is PHP a scalar value? Yes
Is 100 a scalar value? Yes
Is 1.5 a scalar value? Yes
Is FALSE a scalar value? Yes
Is [1,2] a scalar value? No
Is NULL a scalar value? No
Practical usage of PHP is_scalar() function:
- In your program when a function only accept simple value and no complex data types, use is_scalar() function.
- When a filed in your database table only accepts single value, you can use is_scalar() function to ensure it.
- You can use is_scalar() function to detect a non scalar variable so that you can display it properly in the display using functions like print_r() or var_dump() function.
- You can use is_scalar() function before using some function that only operates on single values.
Note:
NULL is not considered a scalar value.
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP is_scalar() Function
is_scalar() is a built-in variable handling function. It is a simple but very effective function to determine whether a value is scalar or not.