PHP Shorthand for isset form POST value

Drew picture Drew · Sep 20, 2011 · Viewed 24.8k times · Source

I am creating a form and am just looking for more efficient ways to do things. What I have so far is:

<p><input type="text" name="transmission" value="" /></p>
<p><input type="text" name="model" value="<?=$model;?>" /></p>

So some of them will have a value already set, and some will be blank. What I want to do is see if the form has been set, and if it has then use $_POST['name'] as the value, if not then use either blank or use the previous variable I have.

<p><input type="text" name="name" value="<?php if isset($_POST['submit'])) { echo $_POST['name']; } else { echo ""; } ?>" /></p>

But there has to be a shorter way to do that.

IF anyone could point me in the direction I would really appreciate it.

Thank you!

Answer

Nazariy picture Nazariy · Sep 20, 2011

You can define variables in beginning of your script before HTML output, for example:

$name = isset($_POST['submit']) ? $_POST['name'] : null;

in your html section you can print $name without worrying it was not defined

<p><input type="text" name="name" value="<?php echo $name ?>" /></p>

Also if $_POST['submit'] does not contain any value you are more likely to receive FALSE statement. To avoid such issues use array_key_exists