23

I have a POST in PHP for which I won't always know the names of the variable fields I will be processing.

I have a function that will loop through the values (however I would also like to capture the variable name that goes with it.)

foreach ($_POST as $entry)
{
     print $entry . "<br>";
}

Once I figure out how to grab the variable names, I also need to figure out how I can make the function smart enough to detect and loop through arrays for a variable if they are present (i.e. if I have some checkbox values.)

jww
  • 97,681
  • 90
  • 411
  • 885
Joseph U.
  • 4,457
  • 10
  • 41
  • 47

4 Answers4

44

If you just want to print the entire $_POST array to verify your data is being sent correctly, use print_r:

print_r($_POST);

To recursively print the contents of an array:

printArray($_POST);

function printArray($array){
     foreach ($array as $key => $value){
        echo "$key => $value";
        if(is_array($value)){ //If $value is an array, print it as well!
            printArray($value);
        }  
    } 
}

Apply some padding to nested arrays:

printArray($_POST);

/*
 * $pad='' gives $pad a default value, meaning we don't have 
 * to pass printArray a value for it if we don't want to if we're
 * happy with the given default value (no padding)
 */
function printArray($array, $pad=''){
     foreach ($array as $key => $value){
        echo $pad . "$key => $value";
        if(is_array($value)){
            printArray($value, $pad.' ');
        }  
    } 
}

is_array returns true if the given variable is an array.

You can also use array_keys which will return all the string names.

newfurniturey
  • 37,556
  • 9
  • 94
  • 102
Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
5

You can have the foreach loop show the index along with the value:

foreach ($_POST as $key => $entry)
{
     print $key . ": " . $entry . "<br>";
}

As to the array checking, use the is_array() function:

foreach ($_POST as $key => $entry)
{
     if (is_array($entry)) {
        foreach($entry as $value) {
           print $key . ": " . $value . "<br>";
        }
     } else {
        print $key . ": " . $entry . "<br>";
     }
}
Unsigned
  • 9,640
  • 4
  • 43
  • 72
Jeffrey Blake
  • 9,659
  • 6
  • 43
  • 65
1

If you want to detect array fields use a code like this:

foreach ($_POST as $key => $entry)
{
    if (is_array($entry)){
        print $key . ": " . implode(',',$entry) . "<br>";
    }
    else {
        print $key . ": " . $entry . "<br>";
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
silvo
  • 4,011
  • 22
  • 26
1

It's much better to use:

if (${'_'.$_SERVER['REQUEST_METHOD']}) {
    $kv = array();
    foreach (${'_'.$_SERVER['REQUEST_METHOD']} as $key => $value) {
        $kv[] = "$key=$value";
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ascci
  • 11
  • 1