Page 1 of 1
PHP isset return blank
Posted: Thu Sep 29, 2005 11:29 am
by bdeonline
I'm trying to find a easier way to test if a variable isset and echo its value on large forms. Basicly I want to be able to echo the varible value if it has one or just be blank if it don't without getting a error and not just hidding the error with @.
Here is the way I am doing it currently:
Code: Select all
<?php echo (isset($form)) ? $form['email'] : ''; ?>
I could create a function to do it also which would be less code but the same amount of overhead any thoughts on what could be done better.
Posted: Thu Sep 29, 2005 11:40 am
by John Cartwright
Code: Select all
foreach ($_POST as $name => $value) {
$form[$name] = (!empty($value) ? $value : '');
}
This will take all your post variables and rest assure you will have no uninitialized variables

.
Although I usually am a little paranoid and always keep an array of "expected" fields..
So I would use something more along the lines of
Code: Select all
$valid = array(
'name',
'email',
'birth'
);
foreach ($_POST as $name => $value) {
if (in_array($name,$valid)) {
$form[$name] = (!empty($value) ? $value : '');
}
}
But you are right, this should be a function, if not a class. (read
viewtopic.php?t=38787#205102) if you are looking for more functionality with your input)
Code: Select all
function ($method, $valid) {
$form = array();
foreach ($method as $name => $value) {
if (in_array($name,$valid)) {
$form[$name] = (!empty($value) ? $value : '');
}
}
return $form;
}
Posted: Thu Sep 29, 2005 12:34 pm
by shiznatix
much less complicated: change isset to !empty
Posted: Thu Sep 29, 2005 12:45 pm
by bdeonline
shiznatix wrote:much less complicated: change isset to !empty
Not sure what you mean wouldn't help much also thinking about it I can't send it to a function to check because if the variable doesn't exsist then it will generate a error instead.
Code: Select all
<?php echo (!empty($form)) ? $form['email'] : ''; ?>
This is the closest easy way to do it but it still puts a error in the error logs