Convert an array to a string PHP

How to convert an array to a string in PHP

Posted by Ervin Adams on April 6, 2023

Convert an array to a string PHP

How to convert an array to a string in PHP

Posted by Ervin Adams on April 6, 2023

In PHP, you can use the implode() function to convert an array into a string. The implode() function takes two arguments:

  1. The first argument is the string that will be used to separate the array elements in the resulting string. This argument is optional, and if it is not specified, the default separator is an empty string.

  2. The second argument is the array that you want to convert to a string.

// Declare an array 
$array = array("Welcome","to", "the", "CodeIt247", "platform");  
    
// Convert array into string
echo implode(" ",$array); //Output: Welcome to the CodeIt247 platform

In this example, the implode() function is used to convert the $array variable into a string. The separator is specified as a space.

You can also use the join() function instead of implode(). They are identical in terms of functionality; join() is just an alias for implode().

// Declare an array 
$array = array("Welcome","to", "the", "CodeIt247", "platform");  
    
// Convert array into string
echo join(" ",$array); //Output: Welcome to the CodeIt247 platform

Both implode() and join() functions are useful when you need to pass an array as a parameter to a function or when you need to output the contents of an array in a specific format.

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question