37

I have a PHP array and want to convert it to a string.

I know I can use join or implode, but in my case array has only one item. Why do I have to use combine values in an array with only one item?

This array is the output of my PHP function which returns an array:

Array(18 => 'Something');

How do I convert this to a string?

Salman Arshad
273k85 gold badges448 silver badges540 bronze badges
asked Jun 7, 2011 at 7:54
1
  • 3
    It depends. What do you want as the resulting string given the array above? Commented Jun 7, 2011 at 7:59

13 Answers 13

40

Is there any other way to convert that array into string ?

You don't want to convert the array to a string, you want to get the value of the array's sole element, if I read it correctly.

<?php
 $foo = array( 18 => 'Something' );
 $value = array_shift( $foo );
 echo $value; // 'Something'.
?>

Using array_shift you don't have to worry about the index.

EDIT: Mind you, array_shift is not the only function that will return a single value. array_pop( ), current( ), end( ), reset( ), they will all return that one single element. All of the posted solutions work. Using array shift though, you can be sure that you'll only ever get the first value of the array, even when there are multiple.

Eric Leschinski
155k96 gold badges422 silver badges337 bronze badges
answered Jun 7, 2011 at 7:58
3
  • 1
    Just ran both functions one million times using this code. That's 1.81 seconds for array_shift, 1.71 seconds for reset. That pretty much means that reset is about 0.0000001 seconds faster per call. I'm sorry, but if you're worried about that, you're the most efficient programmer ever. ;) Commented Jun 7, 2011 at 8:50
  • 2
    There is nothing wrong with using the most efficient way to achieve your goal, but I find array_shift more descriptive of the goal, so I use that. reset( ) is marginally better in performance, yet it doesn't communicate its goal that well, so I opt for array_shift. That's not overkill, it's a well-informed choice. smile. Commented Jun 7, 2011 at 9:10
  • There is a major difference between reset and array_shift though. array_shift will remove the first element from the array and leave the internal pointer intact, while reset preserves the array but resets the internal pointer. Commented Aug 26, 2014 at 9:22
28

Is there any other way to convert that array into string ?

Yes there is. serialize(). It can convert various data types (including object and arrays) into a string representation which you can unserialize() at a later time. Serializing an associative array such as Array(18 => 'Somthing') will preserve both keys and values:

<?php
$a = array(18 => 'Something');
echo serialize($a); // a:1:{i:18;s:9:"Something";}
var_dump(unserialize('a:1:{i:18;s:9:"Something";}')); // array(1) {
 // [18]=>
 // string(9) "Something"
 // }
answered Jun 7, 2011 at 8:15
0
11

A simple way to create a array to a PHP string array is:

<?PHP
 $array = array("firstname"=>"John", "lastname"=>"doe");
 $json = json_encode($array);
 $phpStringArray = str_replace(array("{", "}", ":"), 
 array("array(", "}", "=>"), $json);
 echo phpStringArray;
?>
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Dec 17, 2012 at 2:08
3
  • 1
    Code won't work properly if {, }, : are embedded in string literals. You need a proper parser. Commented Jan 2, 2013 at 14:43
  • 1
    This answer helped me most. Thnx Sven. Commented Apr 2, 2013 at 18:17
  • 2
    Although I'm a bit late: this doesn't seem like the best solution. If you want to do this, simply call var_export($array, true);, it'll do pretty much the same, but better. Commented Jun 25, 2013 at 11:17
8

You can use the reset() function, it will return the first array member.

answered Jun 7, 2011 at 7:58
3
  • It will also rewind array's internal pointer to the first member. Commented Jun 7, 2011 at 8:02
  • 1
    @binaryLV he said that the array has only one member, so I think it won't be a problem. Commented Jun 7, 2011 at 8:03
  • Yeah, that was just an addition - just in case he is going to use reset() with other arrays. Commented Jun 7, 2011 at 8:09
6

implode or join (they're the exact same thing) would work here. Alternatively, you can just call array_pop and get the value of the only element in the array.

answered Jun 7, 2011 at 7:59
5

If your goal is output your array to a string for debbuging: you can use the print_r() function, which receives an expression parameter (your array), and an optional boolean return parameter. Normally the function is used to echo the array, but if you set the return parameter as true, it will return the array impression.

Example:

 //We create a 2-dimension Array as an example
 $ProductsArray = array();
 $row_array['Qty'] = 20;
 $row_array['Product'] = "Cars";
 array_push($ProductsArray,$row_array);
 $row_array2['Qty'] = 30;
 $row_array2['Product'] = "Wheels";
 array_push($ProductsArray,$row_array2);
 //We save the Array impression into a variable using the print_r function
 $ArrayString = print_r($ProductsArray, 1);
 //You can echo the string
 echo $ArrayString;
 //or Log the string into a Log file
 $date = date("Y-m-d H:i:s", time());
 $LogFile = "Log.txt";
 $fh = fopen($LogFile, 'a') or die("can't open file");
 $stringData = "--".$date."\n".$ArrayString."\n";
 fwrite($fh, $stringData);
 fclose($fh);

This will be the output:

Array
(
 [0] => Array
 (
 [Qty] => 20
 [Product] => Cars
 )
 [1] => Array
 (
 [Qty] => 30
 [Product] => Wheels
 )
)
answered Jul 20, 2011 at 14:19
4

You could use print_r and html interpret it to convert it into a string with newlines like this:

$arraystring = print_r($your_array, true); 
$arraystring = '<pre>'.print_r($your_array, true).'</pre>';

Or you could mix many arrays and vars if you do this

ob_start();
print_r($var1);
print_r($arr1);
echo "blah blah";
print_r($var2);
print_r($var1);
$your_string_var = ob_get_clean();
Eric Leschinski
155k96 gold badges422 silver badges337 bronze badges
answered Jun 13, 2012 at 13:17
4

A For() loop is very useful. You can add your array's value to another variable like this:

<?php
 $dizi=array('mother','father','child'); //This is array
 $sayi=count($dizi);
 for ($i=0; $i<$sayi; $i++) {
 $dizin.=("'$dizi[$i]',"); //Now it is string...
 }
 echo substr($dizin,0,-1); //Write it like string :D
?>

In this code we added $dizi's values and comma to $dizin:

$dizin.=("'$dizi[$i]',");

Now

$dizin = 'mother', 'father', 'child',

It's a string, but it has an extra comma :)

And then we deleted the last comma, substr($dizin, 0, -1);

Output:

'mother','father','child'

josliber
44.4k12 gold badges103 silver badges136 bronze badges
answered Oct 22, 2013 at 21:54
2
  • 1
    Here you are writing an answer which is basically human readable piece of text not a database function. There is an automatic process evaluating answers and yours was marked low quality. I suppose it was because it seems to lack an explanation. Commented Oct 23, 2013 at 9:08
  • i added the explanation now :) Commented Oct 23, 2013 at 10:00
3

Use the inbuilt function in PHP, implode(array, separator):

<?php
 $ar = array("parth","raja","nikhar");
 echo implode($ar,"/");
?>

Result: parth/raja/nikhar

Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Mar 24, 2014 at 9:01
2

Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().

<?php
function var_export_min($var, $return = false) {
 if (is_array($var)) {
 $toImplode = array();
 foreach ($var as $key => $value) {
 $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
 }
 $code = 'array('.implode(',', $toImplode).')';
 if ($return) return $code;
 else echo $code;
 } else {
 return var_export($var, $return);
 }
}
?>

http://www.php.net/manual/en/function.var-export.php#54440

answered Mar 24, 2013 at 23:19
2

Convert an array to a string in PHP:

  1. Use the PHP join function like this:

    $my_array = array(4, 1, 8);
    print_r($my_array);
    Array
    (
     [0] => 4
     [1] => 1
     [2] => 8
    )
    $result_string = join(',', $my_array);
    echo $result_string;
    

    Which delimits the items in the array by comma into a string:

    4,1,8
    
  2. Or use the PHP implode function like this:

    $my_array = array(4, 1, 8);
    echo implode($my_array);
    

    Which prints:

    418
    
  3. Here is what happens if you join or implode key value pairs in a PHP array

    php> $keyvalues = array();
    php> $keyvalues['foo'] = "bar";
    php> $keyvalues['pyramid'] = "power";
    php> print_r($keyvalues);
    Array
    (
     [foo] => bar
     [pyramid] => power
    )
    php> echo join(',', $keyvalues);
    bar,power
    php> echo implode($keyvalues);
    barpower
    php>
    
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Jan 4, 2014 at 17:03
1

Convert array to a string in PHP:

Use the PHP join function like this:

$my_array = array(4,1,8);
print_r($my_array);
Array
(
 [0] => 4
 [1] => 1
 [2] => 8
)
$result_string = join(',' , $my_array);
echo $result_string;

Which delimits the items in the array by comma into a string:

4,1,8
Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Dec 13, 2013 at 9:41
0

For completeness and simplicity sake, the following should be fine:

$str = var_export($array, true);

It does the job quite well in my case, but others seem to have issues with whitespace. In that case, the answer from ucefkh provides a workaround from a comment in the PHP manual.

Peter Mortensen
31.6k22 gold badges110 silver badges134 bronze badges
answered Apr 7, 2014 at 12:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.