Re: Looping through variables

From: Date: Tue, 24 Apr 2001 06:04:09 +0000
Subject: Re: Looping through variables
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-50014@lists.php.net to get a copy of this message
Previously, Ashley M. Kirchner said: > > I have a bunch of variables (through a POST form) that I need to > loop through and check for content. Right now, each one is being > evaluated separately: > > if ($var1 == '') { > $url .= "&var1="; > $error = 1; > } else { > $url .= "&var1=".urlencode(stripslashes($var1)).""; > } > > Then repeat for $var2, $var3, etc., etc... > > Is there a better way of doing this looping instead of writing the > same routine over and over again? // List of variable names $var_list = array ( 'var1', 'var2', 'var3', 'var4' ); while (list($key,$val) = each($var_list)) { if ($$val == '') { $url .= "&".$val."="; $error = 1; } else { $url .= "&".$val."=". urlencode(stripslashes($$val)) .""; } } Of course, if this is all POST variables then you should be able to just use the pre-built array $HTTP_POST_VARS (if track_vars is on). Then you'd do something like this instead: while (list($key,$val) = each($HTTP_POST_VARS)) { if ($val == '') { $url .= "&".$key."="; $error = 1; } else { $url .= "&".$key."=".urlencode(stripslashes($val)).""; } } If you're using GET rather than post, just subtitute $HTTP_GET_VARS. -d -- If a man is standing in the middle of the forest speaking and there is no woman around to hear him... is he still wrong? -George Carlin

« previous php.general (#50014) next »