Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Last active April 13, 2020 13:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcaskill/89a69e4ef71bcc5090fe8274248d6079 to your computer and use it in GitHub Desktop.
Save mcaskill/89a69e4ef71bcc5090fe8274248d6079 to your computer and use it in GitHub Desktop.
PHP : Determine whether a variable or object is empty.

is_var_empty

(PHP 5 >= 5.4)
is_var_empty — Determine whether a variable or object is empty.

Description

boolean is_var_empty( mixed $var )

Alternative to empty() which will resolve stringable and arrayable objects.

Parameters

  • var — The value to be checked.

Return Values

Returns FALSE if var exists and has a non-empty value. Otherwise returns TRUE.

Installation

With Composer

$ composer require mcaskill/php-is-var-empty

Without Composer

Why are you not using composer? Download Function.Is-Var-Empty.php from the gist and save the file into your project path somewhere.

{
"name": "mcaskill/php-is-var-empty",
"description": "Determine whether a variable or object is empty.",
"license": "MIT",
"authors": [
{
"name": "Chauncey McAskill",
"email": "chauncey@mcaskill.ca",
"homepage": "https://github.com/mcaskill"
}
],
"keywords": [
"function"
],
"extra": {
"branch-alias": {
"dev-master": "1.x-dev"
}
},
"require": {
"php": ">=5.4.0"
},
"autoload": {
"files": ["Function.Is-Var-Empty.php"]
}
}
<?php
if (!function_exists('is_var_empty')) {
/**
* Determine whether a variable is empty.
*
* Alternative to {@see empty()} which will resolve stringable and arrayable objects.
*
* @param mixed $var The value to be checked.
* @return boolean Returns FALSE if var exists and has a non-empty value. Otherwise returns TRUE.
*/
function is_var_empty($var)
{
if (!isset($var)) {
return true;
}
if (is_array($var) || ($var instanceof Traversable)) {
$length = 0;
foreach ($var as $val) {
if (!is_var_empty($val)) {
return false;
}
}
return true;
}
if (is_object($var) && method_exists($var, '__toString')) {
$var = strval($var);
}
if (is_string($var)) {
$var = trim($var);
}
return empty($var) && !is_numeric($var);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment