Home > database >  Why does !empty($variable) behave as an integer in this example?
Why does !empty($variable) behave as an integer in this example?

Time:04-18

I am reviewing some of my old code and found this gem. Not sure how I came up with it but it works.

This given code

echo time() - !empty($stored_unix);
echo "\n";
sleep(3);
echo time() - !empty($stored_unix);
echo "\n";
sleep(3);
echo time() - !empty($stored_unix);
echo "\n";

Outputs this:

1650155411
1650155414
1650155417

The documentation says empty() should return a boolean, but clearly here is not being treated as a boolean (nor a 0 or a 1). Does anyone have the answer to this?

EDIT: I am editing this because my approach was wrong, and PHP does not treat !empty($start_time) as an integer > 1, it simply treats it as 1 or 0 which is the numerical representation of true and false.

$start_time = 5;
echo !empty($start_time);

echo "\n";
sleep(3);
echo "\n";
echo time() - !empty($start_time);
echo "\n";
echo time();
echo "\n";
sleep(3);
echo time() - !empty($start_time);
echo "\n";
echo time();
echo "\n";
sleep(3);
echo time() - !empty($start_time);
echo "\n";
echo time();
echo "\n";

Here you can appreciate that it's being treated as 1 and not 5, so I was wrong reproducing this.

Result of the above:

1

1650201075
1650201076
1650201078
1650201079
1650201081
1650201082

CodePudding user response:

this is due to php type juggling.

An example of PHP's automatic type conversion is the multiplication operator '*'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as ints, and the result will also be an int. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

since time(): int returns int and !empty() returns true or false the restult will be an integer where true -> 1 and false -> 0

example: (php -a to access the php interactive shell.)

  1. true 1 = 2;
  2. false 1 = 1;
  •  Tags:  
  • php
  • Related