How Create an Array from the Output of an Array Printed With Print_R

How create an array from the output of an array printed with print_r?

I actually wrote a function that parses a "stringed array" into an actual array. Obviously, it's somewhat hacky and whatnot, but it works on my testcase. Here's a link to a functioning prototype at http://codepad.org/idlXdij3.

I'll post the code inline too, for those people that don't feel like clicking on the link:

<?php
/**
* @author ninetwozero
*/
?>
<?php
//The array we begin with
$start_array = array('foo' => 'bar', 'bar' => 'foo', 'foobar' => 'barfoo');

//Convert the array to a string
$array_string = print_r($start_array, true);

//Get the new array
$end_array = text_to_array($array_string);

//Output the array!
print_r($end_array);

function text_to_array($str) {

//Initialize arrays
$keys = array();
$values = array();
$output = array();

//Is it an array?
if( substr($str, 0, 5) == 'Array' ) {

//Let's parse it (hopefully it won't clash)
$array_contents = substr($str, 7, -2);
$array_contents = str_replace(array('[', ']', '=>'), array('#!#', '#?#', ''), $array_contents);
$array_fields = explode("#!#", $array_contents);

//For each array-field, we need to explode on the delimiters I've set and make it look funny.
for($i = 0; $i < count($array_fields); $i++ ) {

//First run is glitched, so let's pass on that one.
if( $i != 0 ) {

$bits = explode('#?#', $array_fields[$i]);
if( $bits[0] != '' ) $output[$bits[0]] = $bits[1];

}
}

//Return the output.
return $output;

} else {

//Duh, not an array.
echo 'The given parameter is not an array.';
return null;
}

}
?>

Recreate original PHP array from print_r output

function print_r_reverse($in) {
$lines = explode("\n", trim($in));
if (trim($lines[0]) != 'Array') {
// bottomed out to something that isn't an array
return $in;
} else {
// this is an array, lets parse it
if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match[1];
$spaces_length = strlen($spaces);
$lines_total = count($lines);
for ($i = 0; $i < $lines_total; $i++) {
if (substr($lines[$i], 0, $spaces_length) == $spaces) {
$lines[$i] = substr($lines[$i], $spaces_length);
}
}
}
array_shift($lines); // Array
array_shift($lines); // (
array_pop($lines); // )
$in = implode("\n", $lines);
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
$pos = array();
$previous_key = '';
$in_length = strlen($in);
// store the following in $pos:
// array with key = key of the parsed array's item
// value = array(start position in $in, $end position in $in)
foreach ($matches as $match) {
$key = $match[1][0];
$start = $match[0][1] + strlen($match[0][0]);
$pos[$key] = array($start, $in_length);
if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
$previous_key = $key;
}
$ret = array();
foreach ($pos as $key => $where) {
// recursively see if the parsed out value is an array too
$ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
}
return $ret;
}
}

not my code, found here in the comments: print_r
'Matt' is the owner

How can I echo or print an array in PHP?

This will do

foreach($results['data'] as $result) {
    echo $result['type'], '<br>';
}

how to echo print_r() array output

Loop the array like shown below. The key is the email, then use implode() on the value

foreach ($array as $key => $value) {
echo "key: " , $key , PHP_EOL;
echo "value: " , implode(' ',$value) , PHP_EOL , PHP_EOL;
}

Output:-

key: one@gmail.com
value: 70,80 90,100

key: two@gmail.com
value: 10

Demo at:

https://3v4l.org/gXJcP or https://3v4l.org/rN9LV

PHP print_r function does not nest the printed array

This happens simply because you are printing plaintext straight to your webpage, which automatically reformats text, luckily there is a solution.

The following code will "pretty print" your PHP arrays.

echo "<pre>".print_r($array, true)."</pre>";

The HTML <pre> tag is used for indicating preformatted text. The code
tag surrounds the code being marked up.

https://www.tutorialspoint.com/html/html_pre_tag.htm

The 2nd parameter of print_r() tells the function to capture the output of print_r() instead of printing it as plaintext. Learn more on the PHP docs.

These two methods put together make the output to be "prettified".


As noted by dognose in the comments, if you don't want to use <pre> tags for whatever reason, you can simply view the source code of the page you are working on and it will show the array in a "nice" fashion.

Example posted by dognose:
Sample Image


Function

I've written a little pretty print function that will allow you to do this a bit easier...

function print_p($arr) {
return "<pre>".print_r($arr, true)."</pre>";
}

This can save you a lot of time/effort of typing the pre tags every time. Usage:

echo print_p($array);

Create variable from print_r output

Amusingly the PHP manual contains an example that tries to recreate the original structure from the print_r output:

print_r_reverse()

http://www.php.net/manual/en/function.print-r.php#93529

However it does depend on whitespace being preserved. So you would need the actual HTML content, not the rendered text to pipe it back in.

Also it doesn't look like it could understand anything but arrays, and does not descend. That would be incredibly difficult as there is no real termination marker for strings, which can both contain newlines and ) or even [0] and => which could be mistaken for print_r delimiters. Correctly reparsing the print_r structure would be near impossible even with a recursive regex (and an actual parser) - it could only be accomplished by guesswork splitting like in the code linked above.. (There are two more versions there, maybe you have to try them through to find a match for your specific case.)

How to print an Array on one line

$arrayString = print_r($array, true);
echo str_replace("\n", "", $arrayString);

The second value of print_r lets the function return the value instead of printing it out directly.

Pretty print using print_r() outputs single-line, not tiered/organized (PHP)

Thank you @CBroe! Solved.

By changing the default return value to TRUE (for the return parameter), I'm getting pretty print!

THIS: echo "<pre>".print_r($array,true)."</pre>";

NOT THIS: echo "<pre>".print_r($array)."</pre>";



Related Topics



Leave a reply



Submit