0

I have been struggling with a problem working in both html and php. in my html, i have a form tag that includes:

<input type="text" name="car1" size="4" value="" /> car1

In my php, i have this:

$car1 = 'my favorite car is ' . $_POST['car1'];
echo $car1;

I am trying to figure out a way so that when the user does not input anything into the car1 field in html, echo $car1; will print nothing or blank but when the user does input something, $car1 will echo my favorite car is $car1.

I tried using if(empty() and if(isset() but i am having issues to make it work for some reason.

Any ideas to do this properly? thanks for the help!

4 Answers 4

1
if(!empty($_POST['car1'])){
$car1 = 'my favorite car is ' . $_POST['car1'];
echo $car1;
}
Sign up to request clarification or add additional context in comments.

3 Comments

The only minor problem with this is that empty("0") will evaluate to true… So if the value of car1 is "0", the $car1 = ... won't get evaluated.
I somehow didnt have that dot between the string and the variable! thanks for the help!
@David i know this, the manual says this, but for this instance, as there is no car called "0" it seemed like a valid responce, i used the context provided by the poster to decide the appropriate approach, which is how things should be written.
0

Try:

if ($_POST["car1"] !== "") {
    $car1 = "my favourite …";
} else {
    $car1 = "";
}

2 Comments

The only minor problem with your answer is that it will throw notices if $_POST['car1'] does not exist. :)
Ah, very true! Unless, of course, you're pro enough to be rolling with error_reporting = 0.
0

As simple as:

if (!empty($_POST['car1'])) {
    echo 'my favorite car is ' . htmlentities($_POST['car1']);
}

See here which values are regarded as empty. If you want more control, use something like:

if (isset($_POST['car1']) && $_POST['car1'] !== '')

You should

  • always check whether keys in $_POST are !empty or isset before using them
  • always HTML escape user supplied data for output
  • use labels:

    <input type="text" name="car1" size="4" id="car1Input" value="" />
    <label for="car1Input">car1</label>
    

2 Comments

As I noted on Dagon's answer: the only minor problem with this is that empty("0") will evaluate to true… So if the value of car1 is "0", the $car1 = ... won't get evaluated.
@David Sure, in that case use isset instead. Depends on what values you regard as "empty".
0
if(isset($_POST["car1"]))
    $car1 = "my favorite car is $_POST["car1"]";
else 
    $car1 = "";
return $car1 //if function or
echo $car1; //if general

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.