PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP HTTP & HTTPSPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP NamespacesPHP OOP Autoloading

PHP Forms Required Inputs

So far, any input in our form was optional. But, when we create forms, we need to have required input fields. As an example, email field should not empty, otherwise it should show an error.

In PHP, we use empty() function to check whether an input is empty or not. This function returns true on following cases.

  • "" - In an empty string
  • 0 - 0 as an integer
  • 0.0 - 0 as a float
  • "0" - 0 as string
  • null
  • false
  • [] - empty array

In the following example, form and handler will be on the same script. Then, we will show error messages inside the forms.

Tip: Data of non-form element (<div>, <span>, etc.) inside a form will not be submitted.

Required Input Fields


	// request method is post
	// now handle the form data

	// declare name and email variables
	$name = $email = '';

	if (empty($_POST['name'])) {
		$nameError = 'Name should be filled';
	} else {
		$name = trim(htmlspecialchars($_POST['name']));

	if (empty($_POST['email'])) {
		$emailError = 'Please add your email';
	} else {
		$email = trim(htmlspecialchars($_POST['name']));

	<title>PHP Forms</title>
	<style type="text/css">
		.error {

<form method="POST" action="">
	Name: <input type="text" name="name">
	<span class="error"><?php if (isset($nameError)) echo $nameError ?></span>

	Email: <input type="text" name="email">
	<span class="error"><?php if (isset($emailError)) echo $emailError ?></span>
	<input type="submit" name="submit">


Run Example ››

Tip: If there is only one statement inside a if conditional, you can ommit curly braces.
Ex: <?php if (isset($nameError)) echo $nameError ?>

Visit PHP Help group to get some help from experts.
Profile Picture
Supun Kavinda
I'm the Founder of Hyvor, Web Developer, Physics Lover, Flutist, and a Table Tennis Player.
My Websites