How to convert two-dimensional array into string in php

PHPz
Release: 2023-04-23 16:12:38
Original
619 people have browsed it

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)
Copy after login
  • 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;
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template