PHP empty() function – Check variable is empty or not



PHP empty() Function

The empty() function is used to check whether a variable empty or not.

empty  function syntax

empty(“variable”);

The empty() function returns true or false value.

  • True – If variable has empty or zero(0) value.
  • False – If variable has non-empty and non-zero value.

Example of empty() function

Here, declare two variable one with empty  string value and another with some text value and check variable whether is empty or not using php empty() function.

<?php
$str1=0;
$str2='Meera';

if(empty($str1))
{
echo "The str1 is empty or 0 <br/>"; 
}
else
{
echo "The str1 is not empty <br/>";
}

if(empty($str2))
{
echo "The str2 is empty or 0 <br/>";
}
else
{
echo "The str2 is not empty";
}
?>

The output is empty() function :

The str1 is empty or 0
The str2 is not empty


PHP  empty() function example

Here, we design a php form with a textbox and a button control. here we check whether the textbox values is empty or not. If textbox value is empty then display error message “Enter text”, and if textbox has some value then return a success message on php form.

<html>
</head><title>PHP empty() function example</title>
</head>
<body>
<form method="post">

Enter value :<input type="text" name="str1"><br/>
<input type="submit" value="Submit" name="Submit1"><br/><br/>

<?php
if(isset($_POST["Submit1"]))
{
if(empty($_POST["str1"]))
{
echo "Enter Value";
}
else
{
echo "The Value = ". $_POST["str1"];
}
}
?>
</body>
</html>

The output is :

PHP empty() function example
PHP empty() function example

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *