How to join array elements into a string in PHP?

Member

by jasen , in category: PHP General , 6 months ago

How to join array elements into a string in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 6 months ago

@jasen 

In PHP, you can join array elements into a string using the implode() function.


The implode() function takes two arguments: the first argument is the separator that you want to use to join the array elements, and the second argument is the array that you want to join.


Here's an example:

1
2
3
$fruits = array('apple', 'banana', 'orange');
$fruits_string = implode(', ', $fruits);
echo $fruits_string;


In this example, the implode() function joins the elements of the $fruits array with a comma and a space as a separator, and stores the resulting string in the $fruits_string variable. The echo statement then outputs the resulting string, which would be:

1
apple, banana, orange


You can use any separator you like, such as a space, a dash, or a newline character.