Home  >  Article  >  Backend Development  >  How to convert array to string in php?

How to convert array to string in php?

青灯夜游
青灯夜游Original
2020-07-20 11:42:104275browse

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 array to string in php?

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 = [&#39;Lucy&#39;,&#39;Mike&#39;,&#39;Jery&#39;,&#39;Haly&#39;];
$str = implode(&#39;,&#39;, $arr);
   var_dump($str);
?>

Output:

string &#39;Lucy,Mike,Jery,Haly&#39; (length=19)

Example 2: Separate array elements with different characters

<?php
    $arr = array(&#39;Hello&#39;,&#39;World!&#39;,&#39;I&#39;,&#39;love&#39;,&#39;Shanghai!&#39;);
    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 = [&#39;Lucy&#39;,&#39;Mike&#39;,&#39;Jery&#39;,&#39;Haly&#39;];
$str = &#39;&#39;;
foreach ($arr as $key => $value) 
{
	$str .=&#39;,&#39;.$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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn