RAABBIT
RAABBIT

Reputation: 17

Empty and Isset functions in php

I am working on a project. For my project, it requires user to enter inflation rate and rate of return of investment. If the user didn't enter anything, it will have default values of 3 and 4 respectively. Then if the user entered whatever value, it will be the value. (if the user entered 0, it will still post the 0. I have tried the following code but the default values do not work. Thank you for your time.

<html>
<p>
<b>Expected rate of return for investment (%):&nbsp;&nbsp;&nbsp;&nbsp;</b>
<input type="number" value="<?php echo $_POST['rinvestment'];?>"  min = "0" placeholder= "4" name="rinvestment" />
</p>

<p>
<b>Inflation Rate (%): </b>
<input type="number" value="<?php echo $_POST['inflation'];?>" min = "0" step = "0.1" name="inflation" placeholder= "3"/>
</p>

 <?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['rinvestment'])){
$rinvestment=$_POST['rinvestment'];
}
else {
$rinvestment = 4;
}


if (isset($_POST['inflation'])){
$inflation=$_POST['inflation'];
}
else {
$inflation = 3;
}
}
?>

Upvotes: 0

Views: 66

Answers (2)

Acharya Anurag
Acharya Anurag

Reputation: 661

The purpose of the isset() variable is just as the name suggests - to check if a particular variable is set, i.e. if it exists.

In your case, despite the user not setting any values, the $rinvestment and $inflation variable are being sent, albeit as a null variable. Now since the isset() function always find the variable, it always returns true. This is why your code is not working.

You need to check for an empty variable to satisfy your condition, i.e.

if(!empty($inflation))
{
    //set default value
}

Although this gets your job done, it is recommended to check for isset of the POST variables to avoid errors.

Upvotes: 2

jmattheis
jmattheis

Reputation: 11115

isset() only checks if the value is set, the value can still be empty so try something like

if(isset($_POST["rinvestment"]) && !empty($_POST["rinvestment"])) {
    $rinvestment=$_POST['rinvestment'];
}
else {
    $rinvestment = 4;
}

if you want the if the user has 0 in the input field that it uses the default value, use this:

if(isset($_POST["rinvestment"]) && (int) $_POST["rinvestment"] > 0) {
    $rinvestment=$_POST['rinvestment'];
}
else {
    $rinvestment = 4;
}

Upvotes: 0

Related Questions