Home  >  Article  >  Backend Development  >  How to convert two-dimensional array into string in php

How to convert two-dimensional array into string in php

PHPz
PHPzOriginal
2023-04-23 10:20:56565browse

In PHP, we can use the implode() function to convert a two-dimensional array into a string. The implode() function is a function that combines array elements into a single string. Its usage is as follows:

implode(separator,array)
  • separator: Optional parameter, which is the string separator. The default is the empty string.
  • array: required parameters, to be combined into an array of strings.

When converting a two-dimensional array into a string, each sub-array needs to be converted into a string first and then combined using the implode() function. The following is an example code:

$array = array(
            array('apple','banana'),
            array('cherry','peach'),
            array('watermelon','orange')
         );

foreach($array as &$value){
    $value = implode(',',$value);
}

$string = implode(';',$array);
echo $string;

Code explanation:

First define a two-dimensional array $array, which contains 3 arrays. Then loop through the array, use the implode() function to convert the subarray into a string, and store the result in the original array. Finally, use the implode() function to combine the subarray strings into a string, using semicolons as delimiters. Finally, the string is output to the screen.

The output of the above code is as follows:

apple,banana;cherry,peach;watermelon,orange

That is, we successfully converted the two-dimensional array into a string.

The above is the detailed content of How to convert two-dimensional array into 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