The PHP "empty($var)" function (or language construct) is a handy function that I use a lot. It replaces all of the following checks:
- isset($var)
- $var !== 0
- $var !== 0.0
- $var !== ""
- $var !== "0"
- $var !== null
- $var !== false
- count($var) > 0 // if array
This is particularly useful for integers, but can also be useful for checking strings and floats. It replaces a bunch of conditions you'd otherwise have to type.
I've had some disagreements over my frequent usage of empty(). There are those who believe explicit value checks are important to code readability. My response is to ask why a longer line of code is any more readable. There are also those who consider '0' to be non-empty, in which case the use of empty() would not be appropriate. However, the majority of the time when you use empty(), it will be to check a MySQL ID value, which will (should) always be greater than 0.
Consider the following example:
if (!empty($input['state_id'])) {
// Add state ID to query
$person->where('state_id', '=', $input['state_id']);
}
In this case, we're making sure the user has selected a state in a form's drop-down field and then adding the state ID condition to an existing query. This would throw an exception if you used isset() and $input['state_id'] is an empty string, so you'd have to add that check as well.
So why not replace that extra code with a simple empty() statement?
Comments
Post a Comment