0

I have a problem: I need to turn an array into a string and pass it to a function for debugging output.

I cannot directly output the string with print_r, I need to join it with some other strings and pass it to a function.

Google did not bring any results that display the array in a human-readable way without directly printing them. I need a string which I can pass to another function.

4
  • try implode() and show also you expected output with code Commented Apr 29, 2014 at 7:07
  • Please post a sample string, your expected output and the code you've tried so far to achieve the result. Commented Apr 29, 2014 at 7:08
  • You could use $str = print_r($someData,true) Commented Apr 29, 2014 at 7:08
  • possible duplicate of Convert array to string Commented Apr 29, 2014 at 7:09

3 Answers 3

4

You can use the print_r() function like this:

$myarray = ['a', 'b', 'c'];
$string = print_r($myarray, true);
echo $string;

The optional boolean flag as second parameters makes the function return a string instead of directly sending it to the output.

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

2 Comments

To show it in a formatted manner, you can wrap it around '<pre>' tags: $string = '<pre>' . print_r($myarray, true) . '</pre>';
@SupriyaRajgopal Sure, but that is not the goal here (according to the OP) and, important, that only works for HTML based output, so only if you use a browser. Such attempts don't make sense in other situations, for example when using PHP an CLI.
0

print_r uses an optional parameter to set to true to return the string instead of outputting it :

$array = array('foo', 'bar', array('baz' => true, 'test' => 42));
$stringifiedArray = print_r($array, true);
/* $stringifiedArray == "
    Array
    (
        [0] => foo
        [1] => bar
        [2] => Array
            (
                [baz] => 1
                [test] => 42
            )

    )
"
*/

Otherwise, I can see two ways, but both are not as easily readable by a human :

  • json_encode :

$stringifiedArray = json_encode($array, true); // $stringifiedArray == "["foo","bar",{"baz":true,"test":42}]"

  • serialize :

$stringifiedArray = serialize($array, true); // $stringifiedArray == "a:3:{i:0;s:3:"foo";i:1;s:3:"bar";i:2;a:2:{s:3:"baz";b:1;s:4:"test";i:42;}}"

Comments

0

You could also try <?php implode(', ', $array); ?>

Comments

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.