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

1
  • 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. Commented Apr 9, 2010 at 8:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Wow. PHP never ceases to amaze me. It's got a function for EVERYTHING. Thanks man for uncovering this gem.
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.
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.
@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 de2.php.net/manual/en/language.variables.variable.php
@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 Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.