0

I have a function that spits out an array using print_r and would like to capture the information inside a variable to input it into a function for a specific use case. I've simplified the output to make it easier to understand.

[fruit] => 'banana'
[color] => 'yellow'
[sizes] => array('small', 'medium')

I would like it formatted as so:

$var = 'fruit' => 'banana', 'color' => 'yellow', 'sizes' => array('small', 'medium');

This way I can copy and paste the output of the first and assign it to a new default variable.

neoian
  • 33
  • 3
  • Consider using [JSON](http://www.php.net/manual/en/function.json-encode.php). – kojiro Oct 15 '13 at 18:59
  • 2
    I don;t understand why you are copy/pasting anything? Why not just pass the variable into the function? – Mike Brant Oct 15 '13 at 19:01
  • Would [`var_export()`](http://php.net/manual/en/function.var-export.php) work? – gen_Eric Oct 15 '13 at 19:02
  • @Mike - It's just for use as a default variable. I am, but I was just wondering if there was a quicker way than manually editing the array. – neoian Oct 15 '13 at 19:03
  • `var_export()` is what I was looking for. Thanks Rocket. – neoian Oct 15 '13 at 19:04
  • @neoian I think the suggestion by kojiro to serialize might make some sense in your case then. You can use JSON or PHP's native serialization. This makes an array/object into a string which can then be de-serialized back into array/object. – Mike Brant Oct 15 '13 at 19:06

4 Answers4

1

try using var_export(); var_export tutorial

Ryan decosta
  • 455
  • 1
  • 4
  • 10
1

Functions for this:

  1. var_export()
    • Pro: Outputs in a format that can be simply copy/pasted into a PHP script.
    • Con: Has to be pasted into the script. If you use eval() to read it in that's horrible practice and I will cut you.
  2. json_encode()/json_decode()
    • Pro: Widely used across many languages, human-readable, easy to understand.
    • Con: Not natively supported in older versions of PHP
  3. serialize()/unserialize()
    • Pro: Available in all versions of PHP
    • Con: Makes use of non-printing characters [like NULL bytes] that can cause problems with IO workflows that are not explicitly aware of this fact.
Sammitch
  • 30,782
  • 7
  • 50
  • 77
  • `var_export()` works perfectly fine for what I am doing. It's a list of states and their latitudes and longitudes. I'll end up putting them in the database if the need arises, but for now this works well. – neoian Oct 15 '13 at 19:46
0

Try wrapping it with <pre></pre> tag, so it will look like that :

echo '<pre>';
var_dump($var);
echo '</pre>';
Mehdi Karamosly
  • 5,388
  • 2
  • 32
  • 50
0

Might also consider print_r which operates similarly but provides a second argument that, when set to 'true', will return the value as a variable rather than printing it to STDOUT.

drobert
  • 1,230
  • 8
  • 21