Friday 24 February 2017

php - Why is if(empty(strlen(trim($_POST['name'])))) invalid?





I have a if statement check to see if a string is empty



if(empty(strlen(trim($_POST['name'])))){
$error_empty = true;
}



gives me this error:




Fatal error: Can't use function return value in write context in C:\xampp\htdocs\requestaccess\index.php on line 51



Answer



empty is not a function -- it's a "language construct" that prior to PHP 5.5 can only be used to evaluate variables, not the results of arbitrary expressions.



If you wanted to use empty in exactly this manner (which is meaningless) you would have to store the result in an intermediate variable:




$var = strlen(trim($_POST['name']));
if(empty($var)) ...


But you don't need to do anything like this: strlen will always return an integer, so empty will effectively be reduced to checking for zero. You don't need empty for that; zero converts to boolean false automatically, so a saner option is



if(!strlen(trim($_POST['name']))) ...



or the equivalent



if(trim($_POST['name']) === '') ...

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...