Wednesday, February 27, 2019

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...