Jump to content

Variable variables


23.12.2012

Recommended Posts

I'm trying to manipulate a POST request, so that I can sanitize a lot of variables with fewer lines. So I've got this code

foreach($_POST as $key => $value) {		$$key = sanitize($_POST[$key]);}

which I want to expand into

$variable = sanitize($_POST['variable']);

I'm not sure if it's achievable, and if it's not, is there a way to accomplish what I want to do? Thanks in advance!

Link to comment
Share on other sites

Your code pieces do the same thing. It's just that the first works for all variables, while the second works only for a specific variable.The first code piece could actually be written as

foreach($_POST as $key => $value) {	$$key = sanitize($value);}

but that too is equivalent.So... what is it that you want to do really? You have both solutions... are you trying to include/exlude a certain variable from sanitization for whatever reason? If so, you can place a condition within the loop to only apply (or not apply) the sanitization if a condition is met, e.g.

foreach($_POST as $key => $value) {	switch($key) {	case 'variable':	case 'anotherVariable':		//The following is executed only if the $key is one of the cases.		$$key = sanitize($value);	}}

or

foreach($_POST as $key => $value) {	switch($key) {	case 'variable':	case 'anotherVariable':		break;	default:		//The following is executed only if the $key is NOT one of the cases.		$$key = sanitize($value);	}}

Link to comment
Share on other sites

I'm sorry, I was missing exactly the point of it. It was doing what I wanted it to do, but I didn't know it was :) /me dumb. Thanks a lot!

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...