Convert Array to String PHP

There is always an issue with manipulating arrays in PHP. Although they are widely used and fully supported, PHP faces a few drawbacks when working with arrays.

For example, to echo a single element of an array, you can convert the array to a string and print it on the screen.

In this tutorial, you will learn how to convert a PHP array to a string.

Using PHP Implode() Function

The PHP implode() function is a common method when working with arrays. It allows you to join elements in an array using a specified delimiter. The function returns the elements joined in a string format. Hence the function is handy when converting an array to a string.

NOTE: The function also provides the join() method as an alias.

The syntax of the function is as shown below:

implode(string $delimiter, array $array);

The above function takes two arguments: a delimiter (also known as a separator) and an array, respectively.

The following example shows you how to convert an array to a string using the implode function.

    $mean = array("MongoDB", "Express", "Angular", "NodeJS");
    echo $mean;
    $imploded = implode(" ", $mean);
    echo "\n", $imploded, "\n";

This allows the function to return each element in the array as a single sentence.

The example output is as shown:

PHP Notice:  Array to string conversion in /home/ubuntu/strings.php on line 4
MongoDB Express Angular NodeJS

NOTE: PHP will return a notice message if you run the echo method against an array.

You can also use another delimiter in the method as:

    $mean = array("MongoDB", "Express", "Angular", "NodeJS");
    $imploded = implode(", ", $mean);
    echo "\n", $imploded, "\n";

The resulting output is as shown:

MongoDB, Express, Angular, NodeJS

Using PHP json_encode() Function

The other way to convert an array to a string is the json_encode() function. This built-in method allows you to convert an array to a JSON string.

Take a look at the example shown below:

    $mean = array("MongoDB", "Express", "Angular", "NodeJS");
    $json_data = json_encode($mean);
    print_r ($json_data);

Once we run the above code, we should see the array in JSON format as shown:


Using PHP Serialize() Method

The serialize() method allows you to convert an array to a byte-stream string. Consider the example shown below:

    $mean = array("MongoDB", "Express", "Angular", "NodeJS");
    $serialized = serialize($mean);
    print_r ($serialized);

Running the code should return a serialized string as:



This guide gives you the basics of converting a PHP array into a string using built-in methods.

Stay tuned for more tutorials.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list