What Is Meant by "Scalar Type" in PHP?

Learn about scalar types in PHP

The term "scalar" is used to distinguish a single value (for example, an integer, float, etc.) from a compound data type (such as an array, object, etc.). PHP supports the following four scalar data types:

  1. bool;
  2. int;
  3. float;
  4. string.

You can check whether a value is scalar or not by using the is_scalar() PHP function, for example, like so:

$boolean = true;
$integer = 123;
$float = 1.23;
$string = 'abc';

var_dump(is_scalar($boolean)); // bool(true)
var_dump(is_scalar($integer)); // bool(true)
var_dump(is_scalar($float)); // bool(true)
var_dump(is_scalar($string)); // bool(true)

Since PHP is a dynamically typed language, it is possible to mix different scalar types together. In such cases, PHP automatically determines the type of the expression at runtime.

For example, when you use the string concatenation operator (.), regardless of the type of arguments on either side of it, the type of the expression will be a string:

$int = 123;
$string = 'foo' . $int;

var_dump(is_scalar($string)); // bool(true)
echo gettype($string); // 'string'

Consider another example with the multiplication operator (*), where when, either operand is a float, both operands are evaluated as floats. This results in the expression to be of type float:

$string = '23';
$float = $string * 1.23;

var_dump(is_scalar($float)); // bool(true)
echo gettype($float); // 'double'

Please note that for historical reasons, gettype returns "double" for floats instead of "float".


Hope you found this post useful. It was published . Please show your love and support by sharing this post.