-1

I have the following function.

printArray($_POST);
function printArray($array){
     foreach ($array as $key => $value){
        echo "$key: $value <br>";
    } 
}

I modified it from here... Print $_POST variable name along with value

It gets all my html values along with there variable names and echos them. I need to save the output to variable. I've tried using ob..

printArray($_POST);
ob_start();
function printArray($array){
     foreach ($array as $key => $value){
        echo "$key: $value <br>";
    } 
}
$out = ob_get_contents();
ob_end_clean();
print $out;

and that just gives me nothing. Ive tried just saving my echo to a variable and that gets me closer...

&out = “”
function printArray($array){
     foreach ($array as $key => $value){
        $out = "$key: $value <br>";
    } 
}

but it only gives me the last value in my output. Help me out here what am i doing wrong.

NOTE: I screwed up and forgot to modify one of my functions to show what I was doing, whoops..

  • it's not clear why you want to take a variable $_POST and save it as another variable, but I would recommend turning it into a JSON object, which you can then repurpose in a function or even output to use in javascript. `$json = json_encode($_POST);` – Kinglish Nov 28 '21 at 23:06
  • [print_r](https://www.php.net/manual/en/function.print-r.php) — Prints human-readable information about a variable – Lawrence Cherone Nov 28 '21 at 23:42
  • Why are you trying to use output buffering here to begin with, and not just simple string concatenation? `$output = '';` before the loop, `$output .= "$key: $value
    ";` inside ... then $output should contain what you want(?) after the loop, no?
    – CBroe Nov 29 '21 at 08:56
  • That sounds exactly like I wanted to do, just hadn’t known the right syntax. Thanks man lmao, I’m pretty new to web dev. – Taylor Johnson Nov 29 '21 at 13:45

1 Answers1

0

See screenshot: Postman call and result

<?php
printArray($_POST);
function printArray($array){
    $result = [];
    foreach ($array as $key => $value){
       $result[] = (object)[
            $key => $value
       ];
   } 
   header('Content-Type: application/json; charset=utf-8');
   echo json_encode($result);
}
Joundill
  • 6,828
  • 12
  • 36
  • 50
  • ehhhhh i didn't properly clarify The point is to get an output with just variable names and there corresponding variables to save to a variable... like this. `first_name: Test last_name: Test dob1: dob2: dob3:` – Taylor Johnson Nov 29 '21 at 04:39