0

Okay so I have this page where there is some prices and stuff. But at the end you can give a discount in the form of a percentage.

This percentage is then sent by POST to a new page. And here I need it to display something like "you have been giving a discount of 50%.

But if no discount is given and the percentage field is empty in the POST then it must not display the text.

Right now I got something like this

$procent .= $_POST['percent_discount'];



$text .= 'You have recived a discountf of';

$test = $text . $procent;

But this displays the text no matter what. Any idea on how to get it to only show the text and percentage if the percentage is sent in the POST?

planet260
  • 1,384
  • 1
  • 14
  • 30

5 Answers5

4

You can use isset() to check for a value. Like so:

if(isset($_POST['percent_discount'])){
    // do something if its set here
}else{
    // do something if its not set
}

To be slightly different from the other answers, you could also use a shorthand if:

$myString = (isset($_POST['percent_discount']) ? "You received " .$_POST['percent_discount'] . "!" : "We don't like you. No discount for you!");

etc...

Hope this helps!

laminatefish
  • 5,197
  • 5
  • 38
  • 70
1

You'll want to use the empty() function to see if it's been set, or you could also use isset()

 if (empty($_POST))
        //do your no post thing
 else
        //do your post thing

 //using isset
 if (isset($_POST['percent_discount'])
        //post is set
 else
        //post is not set
Zarathuztra
  • 3,215
  • 1
  • 20
  • 34
0

Use an if statement to check if your post field is empty before adding the text to your output.

if( !empty( $_POST['percent_discount'] ) ) {
    $text .= 'You have recived a discountf of' . $procent;
}

This will work if the post field always exists, if there is a possibility that the field may sometimes not be set at all you can add another check using isset

if( isset( $_POST['percent_discount'] ) && !empty( $_POST['percent_discount'] ) ) {
    $text .= 'You have recived a discountf of' . $procent;
}

Hope that helps

Dan

danbahrami
  • 1,014
  • 1
  • 9
  • 14
0
$procent = isset($_POST['percent_discount'])? $_POST['percent_discount'] : 0;
Yair.R
  • 795
  • 4
  • 11
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Bono Mar 10 '15 at 16:16
0

You have to put conditions when to print the text or When to Not

for example

if(isset($_POST['percent_discount']))
{
    echo 'This is text, it\'ll be shown if the discount is given.';
}

By using conditions, it'll only show the text when the discount is given.

Hope it helps :)

harsimarriar96
  • 313
  • 2
  • 11