How to convert php array to string: 1. Use the implode() function to return a string composed of array elements. The code is "$str = implode(',', $arr);" . 2. Use a loop to traverse the array elements and concatenate them into a string.
How to convert php array to string
Method one, use The built-in implode function
implode() function returns a string composed of array elements.
Note: The implode() function accepts two parameter orders. However, due to historical reasons, explode() does not work. You must ensure that the separator parameter comes before the string parameter.
Note: The separator parameter of the implode() function is optional. However, for backward compatibility, it is recommended that you use two parameters.
Syntax
implode(separator,array)
Parameters
separator is optional. Specifies what is placed between array elements. Default is "" (empty string).
array required. Arrays to be combined into strings.
Note: The implode() function accepts two parameter orders. However, due to historical reasons, explode() does not work. You must ensure that the separator parameter comes before the string parameter.
Example 1:
<?php // 方法一:implode(glue, pieces) $arr = ['Lucy','Mike','Jery','Haly']; $str = implode(',', $arr); var_dump($str); ?>
Output:
string 'Lucy,Mike,Jery,Haly' (length=19)
Example 2: Separate array elements with different characters
<?php $arr = array('Hello','World!','I','love','Shanghai!'); echo implode(" ",$arr)."<br>"; echo implode("+",$arr)."<br>"; echo implode("-",$arr)."<br>"; echo implode("X",$arr); ?>
Output:
Hello World! I love Shanghai! Hello+World!+I+love+Shanghai! Hello-World!-I-love-Shanghai! HelloXWorld!XIXloveXShanghai!
Method 2, use a loop to traverse the array elements and concatenate them into a string
<?php //方法二,利用循环遍历数组元素拼接成字符串 $arr = ['Lucy','Mike','Jery','Haly']; $str = ''; foreach ($arr as $key => $value) { $str .=','.$value; } var_dump($str); ?>
Recommended related tutorials: "PHP Tutorial"
The above is the detailed content of How to convert array to string in php?. For more information, please follow other related articles on the PHP Chinese website!