PHP Array to string: Quick guide

Basically, the conversion from a PHP Array to a string can be easily done by the implode() function. So, here you will find some examples.

<?php
$array = array('One','Two','Three','Four');
$string = implode(" ",$array);
echo $string;
?>

Output:

One Two Three Four

So, the variable $string has now the contents of the PHP Array. The implode() function usage is: implode(separator,array);

For example, some more ways on how you can convert a PHP array to string:

CHEAP WEB HOSTING
<?php
$array = array('One','Two','Three','Four');
echo implode("-",$array)."<br>";
echo implode(",",$array)."<br>";
echo implode("+",$array)."<br>";
echo implode("=",$array)."<br>";
?>

More info on the implode() function can be found here.

Multidimensional PHP Array to String

Maybe in case you need to convert a multidimensional array into a string, you may want to use the print_r() function. This is also called “array with keys”. By adding “true” as its second parameter, all the contents of the array will be cast into the string.

<?php
$string = print_r($array, true);
?>

Example:

<?php

$array[1]['name'] = "John";
$array[1]['phone'] = "+1 888 9567834";
$array[2]['name'] = "Doe";
$array[2]['phone'] = "+44 32 5600 673";

$string = print_r($array,true);
echo $string;

?>

Then, the output:

Array
(
    [1] => Array
        (
            [name] => John
            [phone] => +1 888 9567834
        )

    [2] => Array
        (
            [name] => Doe
            [phone] => +44 32 5600 673
        )

)

More info on the PHP function print_r() can be found here.

Example: array to a comma-separated string

In this example, we will have a string with the contents of the array elements separated with commas.

<?php 
$array = array('One','Two','Three','Four'); 
$string = implode(",",$array); 
?>

The output is: “One,Two,Three,Four”.

Example: print array as a string

For this purpose, we will simply use the command print_r(). It will print the raw contents of an array (simple, multidimensional, with keys, etc) as a string.

<?php 
$array = array('One','Two','Three','Four'); 
print_r($array);
?>

Encode an array to a JSON string

For that purpose, we can use the command json_encode().

<?php 
$array = array('One','Two','Three','Four'); 
$json_string = json_encode($array); 
?>

The value of $json_string is:

["One","Two","Three","Four"]

Share and Enjoy !

0Shares
0 0

Leave a Reply

Your email address will not be published. Required fields are marked *