views:

80

answers:

2

Hey all,

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

+8  A: 

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
Wow. PHP never ceases to amaze me. It's got a function for EVERYTHING. Thanks man for uncovering this gem.
Matt
Yeah, there a tools everything in the PHP box. Ever tried doExactlyWhatIWantWithoutAnyProblems($task = "guess_it"); ?
Techpriester
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
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.
Techpriester
@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
@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?
Col. Shrapnel
A: 

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.

Col. Shrapnel
There is nothing wrong with using `var_export` as such. The only somewhat dangerous thing is that the OP wants to have a variable name in it instead of the variable value because he might not be able to make sure the variable name does exist when evaluated.
Gordon
This is design fault and encourage people to write a spaghetti code.
Col. Shrapnel