Monday 16 July 2018

Converting PHP print_r() Output to a String Variable

Converting PHP print_r() Output to a String Variable

The PHP function print_r() is great at outputting a variable in a human-readable format. What if we don’t want it to print to the screen however and instead, for example, want to include it’s output in an email?
The Solution
You might be suprised to learn that you don’t need to find another function or do any fancy output buffering to acheive this (I found this out the hard way!). The print_r() function supports a second parameter that, if set as TRUE will store the results to a variable rather than output them. A simple example would be like so:

  1. $myArray = array('one''two''three');  
  2. $myString = print_r($myArray, TRUE);  
  3. echo $myString;  
The above would then output the following:
  1. Array  
  2. (  
  3.     [0] => one  
  4.     [1] => two  
  5.     [2] => three  
  6. )  

0 comments:

Post a Comment