How to capture the result of var_dump to a string in PHP?\\n



The resultant value of var_dumo can be extracted to a string using ‘output buffering’. Below is an example demonstrating the same −

Example

 Live Demo

<?php    function varDumpToString($var) {       ob_start();       var_dump($var);       $result = ob_get_clean();       return $result;    }    //usage    $data = array('first', 'second', 'third');    $result = varDumpToString($data);    echo $result;

The output control function helps in obtaining the output of a function and saving it to a string variable. In general, the output of a PHP code is usually displayed on a browser.

Output

This will produce the following output −

array(3) { [0]=> string(5) "first" [1]=> string(6) "second" [2]=> string(5) "third" }
Updated on: 2019-12-30T06:38:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements