tags:

views:

69

answers:

3

How would i go about writing a function that would handle the data in an array?

What i mean is, can i use

function CheckStuff($_POST){}

instead of

function CheckStuff($_POST['var1'], $_POST['var2']){}

Reason im asking is i need the function to work through all the values stored in the array and there are quite a few.

+6  A: 

Sure.

function CheckStuff($arr) {
    foreach($arr as $key => $val) {
     //...
    }
}
seanmonstar
+2  A: 

Check out array_filter(). You can define a function, then pass every value of your array through array_filter(), and return only the values that you need:

function verifyData($item)
{
    //do some stuff
    return ($item_is_good) ? true : false;
}

$goodValues = array_filter($_POST,'verifyData');

If you just want to modify each value of $_POST according to some criteria, you could use array_map():

function doSomeStuff($item)
{
    $item = $item++;
}

$output = array_map($_POST,'doSomeStuff');
//all of the values in $_POST have now had 1 added to them
zombat
+1  A: 

I use something like the following to loop through an unknown number of array items.

while( list( $field, $value ) = each( $_POST )) {
  // do something with each array element value
  myFunction( $value );
}

More on the list() function here:

http://www.w3schools.com/PHP/func_array_list.asp

More on the each() function here:

http://www.w3schools.com/PHP/func_array_each.asp

Tim
Any specific reason why you choose `while (list = each)` over `foreach .. as`?
deceze
No reason, just habit. :)
Tim