The behavior of unparenthesized expressions containing both '.' and '+'/'-' will change in PHP 8: '+'/'-' will take a higher precedence

Viewed 7262
$date1 = date('d M Y', strtotime('+' . $i + 1 . 'month'));

This error pops sometimes even I am not calling this function at that point but it works fine when I refresh the page, it seems like some warning.

2 Answers

The issue is that your expression is

'+' . $i + 1 . 'month'

First, it evaluates the leftmost operand, which is '+'. Then it appends $i to that String, resulting in something like '+123'. And then it tries to numerically add 1 to that String, but that will fail, because PHP cannot convert the lefthand-side to a number. In order to solve it, you will need to evaluate $i + 1 first and then evaluate your String.

You can do so implicitly:

$date1 = date('d M Y', strtotime('+' . ($i + 1) . 'month'));

or explicitly:

$monthOffset = $i + 1;
$date1 = date('d M Y', strtotime('+' . $monthOffset . 'month'));

It appears you are using PHP 7.4, which marks certain things as deprecated. These are not errors. Manually add parentheses where appropriate.

Example:

$response = '1234567890';
$header = 'Content-length: ' . strlen($response) + 1;
header($header);

In PHP 5.6, $header would contain 1. In PHP 7.0 to 7.4, it would contain the same, but will also emit a deprecation warning. In PHP 8.0+, it will contain Content-length: 11.

We wrap the arithmetic expression in parentheses, so that to get the correct number is concatenated:

$response = '1234567890';
header('Content-length: ' . (strlen($response) + 1));

So, you can do so implicitly:

$date1 = date('d M Y', strtotime('+' . ($i + 1) . 'month'));
Related