Differences in Arithmetic, Bitwise, and Concatenation Operations
Learn how the migration of arithmetic and bitwise operators from a lower version to PHP 8 might cause problems.
Arithmetic, bitwise, and concatenation operations are at the heart of any PHP application. In this lesson, we’ll learn about hidden dangers that might arise in these simple operations following a PHP 8 migration. We’ll learn about these changes made in PHP 8 so that we can avoid a potential code break in the application. Because these operations are so ordinary, without this knowledge, we will be hard-pressed to discover post-migration errors.
Let’s first have a look at how PHP handles non-scalar data types in arithmetic and bitwise operations.
Handling non-scalar data types in arithmetic and bitwise operations
Historically, the PHP engine has been very forgiving about using mixed data types in an arithmetic or bitwise operation. We’ve already had a look at comparison operations that involve numeric, leading-numeric, and non-numeric strings and numbers. As we learned, when a non-strict comparison is used, PHP invokes type juggling to convert the string to a number before performing the comparison. A similar action takes place when PHP performs an arithmetic operation that involves numbers and strings.
Prior to PHP 8, non-scalar data types (data types other than string
, int
, float
, or boolean
) were allowed in an arithmetic operation. PHP 8 has clamped down on this bad practice and no longer allows operands of the array
, resource
, or object
type. PHP 8 consistently throws a TypeError
when the non-scalar operands are used in an arithmetic operation. The only exception to this general change is that we can still perform arithmetic operations where all operands are of the array
type.
Here is a code example to illustrate arithmetic operator handling differences in PHP 8:
Get hands-on with 1400+ tech skills courses.