Jump to content

Declaring empty variables if the if is false


freelance84

Recommended Posts

Bonjour!

 

A members registration form. One of the fields is the first name:

<td>First name/ initial</td>
<td colspan="2"><input name="forename_1" style="width:150px" type="text" /><i>$no_forename1$check_forename1</i></td>

 

When the form is sent the info is directed back to the same php page. The post is gathered and then checks are run:

if(empty($forename_1)) #check2
{
	$no_forename1 = "First name or initial needed";
}
if(!empty($forename_1)) #check3
{
	if($chosen_forename == 1 && strlen($forename_1)<2)
		{
			$check_forename1 = "Is this name correct?";
		}
}

 

The problem I have lies in the first section of code above: If for example $no_forename1 was never created in the second section of code above then an error is returned saying that $no_forename1 does not exist.

 

One way around this is to declare the variable empty at the start: $no_forename1="";  However this means I have to waste a whole load of lines just to declare the empty variables.

 

Is there a smarter way around this? A way of declaring the variables empty within the if's even if the if's aren't so?

Link to comment
Share on other sites

empty() is a language construct. It will work even if the variable is undefined.

 

See:

daniel@daniel-laptop:~$ cat test.php
<?php
$doesExist = '';
var_dump(empty($hello), empty($doesExist));
?>
daniel@daniel-laptop:~$ php test.php
bool(true)
bool(true)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.