w3resource

PHP: empty() function

Description

The empty() function is used to check whether a variable is empty or not. Often, you may encounter a scenario, when you need to code in fashion if a variable is empty or another thing if it is not so. In these situations, empty function comes to rescue.

Version:

(PHP 4 and above)

Syntax:

empty(var_name)

Parameter:

Name Description Required /
Optional
Type
var_name The variable being checked. Required Mixed*

*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Return value:

FALSE if var_name has a non-empty and non-zero value.

Value Type: Boolean

List of empty things :

  • "0" (0 as a string)
  • 0 (0 as an integer)
  • "" (an empty string)
  • NULL
  • FALSE
  • "" (an empty string)
  • array() (an empty array)
  • $var_name; (a variable declared but without a value in a class)

Example :

<?php
$ivar1=0;
$istr1='Learning empty';
if (empty($ivar1))
{
echo '$ivar1'." is empty or 0. <br />";
}
else
{
echo '$ivar1'." is not empty or 0. <br />";
}
if (empty($istr1))
{
echo '$istr1'." is empty or 0. <br />";
}
else
{
echo '$istr1' ." string is not empty or 0. <br />";
}
?>      

Output:

$ivar1 is empty or 0.
$istr1 string is not empty or 0. 

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous: debug_zval_dump
Next: floatval



PHP: Tips of the Day

PHP: Pass a PHP string to a JavaScript variable (and escape newlines)

<script>
  var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.

Ref : https://bit.ly/34f0Dym