Search code examples
phphtmlformsposthtml-post

If $_POST gives empty value make it 0


$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

Solution

  • You can use the following function to sanitize posted values and return a default value:

    function getPost($key) {
        if(!array_key_exists($key, $_POST))
        return 0; // $_POST[$key] is not defined
        
        return stripslashes(trim($_POST[$key]))?:0; // 0 if empty after cleaning
    }
    

    Then use like below:

    $message .= "First name = ".getPost('first-name')."\n";
    $message .= "Last name = ".getPost('last-name')."\n";
    // ... etc.