PHP is_scalar() Function
The PHP is_scalar() function checks whether a variable is a scalar. The function returns true if the variable is a scalar, otherwise it returns false.
Scalar variables are those containing an int, float, string or bool. Types array, object and resource are not scalar. is_scalar() does not consider NULL to be scalar.
Syntax
is_scalar(variable)
Parameters
variable |
Required. Specify the variable being evaluated. |
Return Value
Returns true if variable is a scalar, false otherwise.
Example:
The example below shows the usage of is_scalar() function.
<?php var_dump(is_scalar(10)); //returns: bool(true) var_dump(is_scalar(10.5)); //returns: bool(true) var_dump(is_scalar(1e5)); //returns: bool(true) var_dump(is_scalar('xyz')); //returns: bool(true) var_dump(is_scalar(true)); //returns: bool(true) echo "\n"; var_dump(is_scalar(array())); //returns: bool(false) var_dump(is_scalar(null)); //returns: bool(false) ?>
The output of the above code will be:
bool(true) bool(true) bool(true) bool(true) bool(true) bool(false) bool(false)
Example:
Consider one more example where this function is used to check all elements of an array if they are a scalar or not.
<?php $Arr = array(10, 10.5, null, false, "xyz", 1e3, array()); foreach ($Arr as $value) { echo "is_scalar(".var_export($value, true).") = "; var_dump(is_scalar($value)); } ?>
The output of the above code will be:
is_scalar(10) = bool(true) is_scalar(10.5) = bool(true) is_scalar(NULL) = bool(false) is_scalar(false) = bool(true) is_scalar('xyz') = bool(true) is_scalar(1000.0) = bool(true) is_scalar(array ( )) = bool(false)
❮ PHP Variable Handling Reference