Home > OS >  If $_POST gives empty value make it 0
If $_POST gives empty value make it 0

Time:06-15

$message .= "First name = ".$_POST['first-name']."\n";
$message .= "Last name = ".$_POST['last-name']."\n";
$message .= "Address line = ".$_POST['address-line']."\n";
$message .= "City = ".$_POST['city']."\n";
$message .= "State = ".$_POST['state']."\n";
$message .= "Country = ".$_POST['country']."\n";
$message .= "Postal code = ".$_POST['postal-code']."\n";

So let's say I submited a form that didnt inculde the first name input

then the result will show up like

First name = 
Last name = something
Address line = something
City = something
State = something
Country = something
Postal code = something

the first name was left empty

now my question is how can I change this so if a $_POST value was empty give 0

to make the result show up like this

First name = 0
Last name = something
Address line = something
City = something
State = something
Country = something
Postal code = something

CodePudding user response:

You can do something like this:

$message .= "First name = ".(isset($_POST['first-name']) && $_POST['first-name']!='' ? $_POST['first-name'] : 0)."\n";

It checks for the existence of the input field and that it is not null. If so, it returns its value, otherwise it returns an integer 0. However, remember to always sanitize the user's input.

CodePudding user response:

Try:

if (!isset($_POST['first-name']) || $_POST['first-name']==''){
    $_POST['first-name'] = 0;
}
  • Related