Cameron Kilgore
Cameron Kilgore

Reputation: 423

DateTime->Format functions unexpectedly with % symbol

I am currently auditing a codebase to transfer to a PHP 7 installation. One of the issues we are seeing is with DateTime->format(), where an argument string gets passed in with a percent sign precluding a value, and in this circumstance, any comparison operator treats it as a string, not as a numeric value

$dto = new \DateTime('now');
if($dto->format("%y") == 20) {

PHP Warning: A non-numeric value encountered in /var/www/html/application/models/User.php on line 225

Has there been a change between PHP 5 and 7 in regards to using the Percent sign in format() statements? Or am I missing something here? It is only a Warning statement, but I would rather keep the error log clear of anything that could take up space.

Upvotes: 0

Views: 189

Answers (1)

Dharman
Dharman

Reputation: 33384

You are checking against an integer in your if statements which leads us to the assumption that the % sign in your format is not required.
While it is not forbidden to include literals such as % in your format string it doesn't have any semantic value, it is just treated as ordinary percent character. This means that the result of your format() would be for example '%19', which is a non numerical string and cannot be compared to an integer. Your if statement will always fail.

If the result you expected was '19', a numerical string, then you can just remove the % from the format string.

$dto = new \DateTime('now');
if($dto->format("y") == 20) {

Upvotes: 2

Related Questions