Steven Oxley
Steven Oxley

Reputation: 6724

What is the best practice for outputting a variable which may or may not contain anything in PHP?

I am developing an application and want to display a form that will be filled in if editing the form, but will not be if the form will be a new entry. I believe the least verbose way of doing this is to have just one form and to suppress any errors for echoing my variables so that nothing will be 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 a good practice, or is there a better way of doing it? Should I make separate views for the new items and for the items to be edited? What are the performance repercussions of doing this?

Upvotes: 0

Views: 177

Answers (3)

Aron Rotteveel
Aron Rotteveel

Reputation: 83203

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;
    }
}

You can then use

<?php echo useDefault($value, 'default value'); ?>

Upvotes: 4

Tom Haigh
Tom Haigh

Reputation: 57835

I think the best way is to always set the variable

if ( ! $new_item) {
    $variable = 'Example';
} else {
    $variable = 'Default value'; 
    //or
    $variable = '';
}

Using the @ error suppression is slow.

edit Note that when you print the variable into the input value attribute, you should first call htmlentities() or htmlspecialchars() on it.

2nd edit

You say in your comment you are fetching the data as on object, in that case you could also do:

class example {
    public $somefield = 'default value';
}

Then if it is an existing record you are editing do something like this, which will cause the returned object to be an instance of 'example':

$record = mysql_fetch_object($result, 'example');

or if it is a new record instanciate it yourself:

$record = new example(); 

Then you always know $record->somefield will be set and you can do :

<form>
    <input type="text" name="somefield" value="<?php echo htmlspecialchars($record->somefield); ?>" />
</form>

Upvotes: 1

benlumley
benlumley

Reputation: 11382

i tend to use:

$variable = (isset($new_item) && $new_item) ? 'Example' : 'Default Value';

Overkill really, but i think going straight for !$new_item throws a notice if it isn't set. You can also switch the second clause out for !empty($new_item) depending on the behaviour you want.

Upvotes: 2

Related Questions