What's the best practice to output a variable that may or may not contain anything in PHP?
I am developing an application and I want to display a form that will be filled when the form is edited, but not if the form is new. I believe the least verbose way to do this is to have only one form and suppress any errors to repeat my variables so that nothing is printed if it is a new form (since the variables will not exist if it is a new form), For example :
<?php
if ( ! $new_item) {
$variable = 'Example';
}
?>
<form>
<input type="text" name="inputbox" value="<?php echo @$variable; ?>" />
</form>
Is this good practice, or is there a better way to do this? Should I make separate views for new elements and for elements that need to be edited? What are the productive consequences of this?
source to share
you can use
<?php echo ((isset($value) && $value != '') ? $value : 'Default'); ?>
A cleaner solution to this problem is to create a helper function that does this for you:
function useDefault($value, $default = '')
{
if (isset($value) && $value != '')
{
return $value;
}
else
{
return $default;
}
}
Then you can use
<?php echo useDefault($value, 'default value'); ?>
source to share
i tend to use:
$variable = (isset($new_item) && $new_item) ? 'Example' : 'Default Value';
Overkill really, but I think you need to go straight !! $ new_item issues a notification if not set. You can also turn off the second sentence for! Empty ($ new_item) depending on the behavior you want.
source to share
I think the best way is to always set the variable
if ( ! $new_item) {
$variable = 'Example';
} else {
$variable = 'Default value';
//or
$variable = '';
}
Using error suppression @
is slow.
edit
Note that when you print a variable in an input value attribute, you must first call htmlentities()
or htmlspecialchars()
on it.
2nd edit
In your comment you say that you are fetching data as an object, in which case you can also do:
class example {
public $somefield = 'default value';
}
Then, if this is an existing entry that you are editing, do something like this, which will cause the returned object to become an instance of "example":
$record = mysql_fetch_object($result, 'example');
or if it's a new entry, do it yourself:
$record = new example();
Then you always know what $record->somefield
will be installed and you can do:
<form>
<input type="text" name="somefield" value="<?php echo htmlspecialchars($record->somefield); ?>" />
</form>
source to share