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?

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)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.