PHP arrays can be converted to strings. 3 conversion methods: 1. Use the implode() function to convert a one-dimensional array into a string, the syntax is "implode (separator, array)"; 2. Use the join() function to return a string composed of array elements. string, the syntax is "join(separator, array)"; 3. Use the foreach statement and the ".=" character splicer, the syntax is "foreach($arr as $value){$str.='separator'.$ value;}".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use the built-in function implode( ) and join() to convert an array to a string; you can also use the foreach statement to convert an array to a string.
Method 1. Use the implode() function
The implode() function can convert a one-dimensional array into a string. The syntax is as follows:
implode($glue,$arr)
Description | |
---|---|
$glue | Optional. Used to set a string, indicating that $glue is used to connect each element of the array together. By default, $glue is an empty string.|
$arr | Required. Arrays to be combined into strings.
<?php $arr = array(1,2,3,4,5,6,7,8,9); var_dump(implode($arr)); var_dump(implode("",$arr)); var_dump(implode(",",$arr)); var_dump(implode("-",$arr)); var_dump(implode("::",$arr)); ?>
Method 2. Use the join() function
join() The function returns a string composed of array elements. The join() function is actually an alias of the implode() function. Its usage and function are the same as the implode() function. You can refer to the above directly.<?php $arr = array(1,2,3,4,5,6,7,8,9); var_dump(join($arr)); var_dump(join(",",$arr)); var_dump(join("-",$arr)); ?>
Method 3: Use the foreach statement and the ".=" character splicing character
<?php function f($arr,$glue){ $str=''; foreach ($arr as $value) { $str .=$glue.$value; } var_dump($str); } $arr = array(1,2,3,4,5,6,7,8,9); f($arr,""); f($arr,","); f($arr,"-"); ?>
PHP Video Tutorial"
The above is the detailed content of Is it possible to convert php array to string?. For more information, please follow other related articles on the PHP Chinese website!