Appl3s
Appl3s

Reputation: 177

Loop through $_GET and $_POST in one go?

is there a way to dynamically access $_GET and $_POST in one go? IE, something like:

$do = array('GET', 'POST');

foreach($do AS $type) {
    foreach (${'_'.type} AS $var=>$val) {
         ... # logic
    }
}

I understand that there is $_REQUEST, but that doesn't tell me source (get or post) and that there are deprecated HTTP_GET_VARS and HTTP_POST_VARS, but those are deprecated.

Clearly, I can just loop individually. The reason why I'm trying to avoid this is that the logic is a little lengthy but also identical. It would be ideal to not have to have a copy of this logic and open myself up to mistakes.

Or am I completely thinking about this the wrong way and there is some other recommended approach?

Thanks!


Thank you

Thank you for the great feedback everyone. I think @deceze answers the question most objectively, but @charlee (and later deceze as well) alludes to a better solution.

In the end, I created a function with logic and then placed that in my foreach, as such:

foreach($_GET AS $var => $val) {
    $_GET[$var] = func($val);
}

I do end up with two foreach()'s, but I appreciate the legibility and increased usability. Thank you again everyone!

Upvotes: 0

Views: 772

Answers (4)

dialogik
dialogik

Reputation: 9552

Merge your arrays with array_merge():

$_GET  = array('one' => 'foo', 'two' => 'bar');
$_POST = array('three' => 'foo', 'four' => 'bar');

$merged = array('_GET' => $_GET, '_POST' => $_POST);

foreach($merged AS $type => $array) {
    foreach ($array AS $var => $val) {
        echo "[{$type}] {$var}: {$val}" . PHP_EOL;
    }
}

Outputs

[_GET] one: foo
[_GET] two: bar
[_POST] three: foo
[_POST] four: bar

And yes, you shouldn't use $_REQUEST, because

it combines COOKIE as well as GET and POST, and the COOKIE data always takes precedence creating the possibility for dangerous "sticky" variables.

Upvotes: 1

deceze
deceze

Reputation: 522442

foreach (array('get' => $_GET, 'post' => $_POST) as $type => $values) {
    foreach ($values as $key => $value) {
        ...
    }
}

Upvotes: 2

Rachitta A Dua
Rachitta A Dua

Reputation: 358

If the logic is identical, you can try using a function. Put your entire code in the function and pass the array that you want to loop through i.e. $_GET or $_POST. If you want to know the source as to whether it is GET or POST, you can try concatenation.

It would help to know what sort of an output you want.

Upvotes: 0

charlee
charlee

Reputation: 1369

If you do care about the source I suggest you loop individually. Its not safe to mash $_POST with $_GET because it would be much easier for hacker to pass data thru GET which is supposed to be POST.

Long logic can always be extracted to a function so you won't have a copy of this logic.

Upvotes: 1

Related Questions