Home > Back-end >  How do I process a block of code with proceed results stored in variable in php?
How do I process a block of code with proceed results stored in variable in php?

Time:02-06

I have a php app where I have snippets of code that I want to process and store in a variable. It might be the output of array data with HTML that I want stored…

$myVar = { // bracket represents starting the store

  foreach ($myarray as $key => $value) {
    echo ‘<td>’ . $value . ‘</td>’;
  }
}// close bracket represents end store

Now the variable would hold the value of what that full echo output would be.

Is there a php function, process, or recommend way of doing this.

I don’t have a framework I’m using on this project.

I am looking for a solution because I don’t know the right approach.

CodePudding user response:

How about:

$myVar = '<td>' . implode('</td><td>', $myArray) . '</td>';

CodePudding user response:

You can use the ob_start and ob_get_clean functions to store the output of the code in a variable:

    ob_start();
    foreach ($myarray as $key => $value) {
      echo ‘<td>’ . $value . ‘</td>’;
    }
    $myVar = ob_get_clean();

ob_start turns on output buffering, which captures all output from your script and stores it in a buffer. The ob_get_clean function then retrieves the contents of the buffer and discards it, leaving you with the contents stored in the $myVar variable.

  •  Tags:  
  • php
  • Related