6

I'm wondering if anyone has a recursive solution to converting an array to a string.

Here's what I mean:

An array $args that has the following contents:

Array
(
    [0] => $hello
    [1] => 411px
    [Jeeves] => Array
        (
            [compiling] => 1
        )

)

Result after calling arr_to_string($args):

array($hello,"411px", "Jeeves" => array("compiling" => 1));

Note: It recognizes the $ sign in front and therefore does not add quotes. It does the same for numbers.

Anyone have any solution or can point me in the right direction?

Thanks! Matt Mueller

Matt
  • 22,224
  • 25
  • 80
  • 116
  • Playing with the code and make a data of it is always dangerous game. Programmer should avoid such cases. Most of time it is much better to treat data as data, in the XML format, for example. – Your Common Sense Apr 09 '10 at 08:00

1 Answers1

17

Looks like you are after

  • var_export — Outputs or returns a parsable string representation of a variable

That won't give you $hello though, because $hello cannot be in an array. It's always just the value of the variable, not the variable name. If you want '$hello', put it into single quotes when inserting it to the array, e.g. insert it as a string, not as a variable.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 1
    Wow. PHP never ceases to amaze me. It's got a function for EVERYTHING. Thanks man for uncovering this gem. – Matt Apr 09 '10 at 07:43
  • Oh and about the $ sign. I'm looking to evaluate it later (when the variable is known) - that's why it shouldn't have single quotes around it. – Matt Apr 09 '10 at 07:48
  • 2
    If you want a more compact representation of the arrays contents, try encoding as JSON with json_encode() or try serialize() for a format that is most reusable by PHP. – selfawaresoup Apr 09 '10 at 07:49
  • @Matt that's impossible. If you do `$myArray[] = $foo`, then the array will contain the *value* of `$foo`, not the name you gave to the variable. Put in the name 'hello' and later evaluate it as variable variable. See http://de2.php.net/manual/en/language.variables.variable.php – Gordon Apr 09 '10 at 07:53
  • 1
    @Matt why not to set this element *after* you've got it's value, not before? And what is the final goal of these unusual movements? – Your Common Sense Apr 09 '10 at 07:54