Python's repr() returns an output where
eval(repr(object)) == object
Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).
So the closest thing in PHP would be
The keyword here is parseable. While functions print_r
and var_dump
will give a certain representation of the data passed to them, they are not easily parseable, nor do they look like PHP expression, which could be eval'd.
Example:
var_export(['foo', 'bar', 1,2,3]);
will give
array (
0 => 'foo',
1 => 'bar',
2 => 1,
3 => 2,
4 => 3,
)
and that is perfectly valid PHP code:
$data = ['foo', 'bar', 1, 2, 3];
$repr = var_export($data, true);
// have to use it with return though to eval it back into a var
$evald = eval("return $repr;");
var_dump($evald == $data); // true
Another option would be to use serialize
to get a canonical and parseable representation of a data type, e.g.
$data = ['foo', 'bar', 1, 2, 3];
$repr = serialize($data);
// -> a:5:{i:0;s:3:"foo";i:1;s:3:"bar";i:2;i:1;i:3;i:2;i:4;i:3;}
var_dump( unserialize($repr) == $data ); // true
Unlike var_export
, the resulting representation is not a PHP expression, but a compacted string indicating the type and it's properties/values (a serialization).
But you are likely just looking for json_encode
as pointed out elsewhere.
Making this a Community Wiki because I've already answered this in the given dupe.
ob_start()
andob_end_clean()
, but I'll use that for now. – Cunningprint_r
does not needob_start
etc -- just specify the second parameter and it will output to a variable. This feature was added in PHP 4.3, so if you think it needsob_start
, you're about ten years behind the times. But in any case, if it's just arrays of strings and numbers you want to output, I'd go with thejson_encode
answer; it's a closer fit to the output in your question. – Doing