PHP isset return blank

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bdeonline
Forum Commoner
Posts: 42
Joined: Sun Jul 18, 2004 10:45 am

PHP isset return blank

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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 :P.
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; 
}
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

much less complicated: change isset to !empty
bdeonline
Forum Commoner
Posts: 42
Joined: Sun Jul 18, 2004 10:45 am

Post 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

Code: Select all

<?php echo @$form['email']; ?>
Post Reply