getting requested variables in another way

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
User avatar
harrison
Forum Commoner
Posts: 30
Joined: Thu Jun 09, 2005 12:23 am

getting requested variables in another way

Post by harrison »

hi, this is my first post here.
I observed most of our codings regarding the ways to get $_POST variables.

Code: Select all

$lname = (isset($_POST['lname'])?$_POST['lname']:'');
$fname = (isset($_POST['fname'])?$_POST['fname']:'');
$address = (isset($_POST['address'])?$_POST['address']:'');
// etc.
I am wondering if i could do this:

Code: Select all

$varnames = array('lname','fname','address');
foreach($varnames as $var){
$($var) = (isset($_POST[$var])?$_POST[$var]:'');
}
... without messing with any rules or sacrificing memory resources?
Syranide
Forum Contributor
Posts: 281
Joined: Fri May 20, 2005 3:16 pm
Location: Sweden

Post by Syranide »

that is possible, or you just create a function which takes the two arguments, one value, and one default (which could default to '').

and if the value is NULL is returns the default instead.

thus making it like this

$lname = default( $_POST['lname'] );

NOTE: but, yes your solution works, however, I would still proceed with caution, as you shouldn't commonly use default values for user-submitted data, you should instead use "isset" and adapt according to what you get. as, getting fname, but not lname would certainly prove to be wrong and shouldn't proceed with registering him without his lname (e.g.).
User avatar
harrison
Forum Commoner
Posts: 30
Joined: Thu Jun 09, 2005 12:23 am

Post by harrison »

thanks, sir.
i saw a version of that function

Code: Select all

$lname = either($_POST['lname'],DEFAULT_LNAME);
which chooses the default value if first argument is null or not set.
Post Reply