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

How to convert array into string in php

PHPz
PHPzOriginal
2023-04-24 15:48:14974browse

The array in PHP is a very commonly used data structure, which can be used to store a series of data. Sometimes we need to convert an array into a string, or a string into an array. This article will describe how to perform these conversion operations.

1. Convert array to string

  1. implode() function

implode() function can connect the elements in the array with strings. Returns the concatenated string.

Syntax:

implode(连接符, 数组);

The connector is the separator that connects array elements and can be any string. For example, use the "," delimiter to connect array elements:

$arr = array('apple','orange','banana');
$str = implode(',', $arr);

The result is:

"apple,orange,banana"
  1. json_encode() function

json_encode() function can Encode the array into JSON string format. JSON is a lightweight data exchange format that is easy to read and write. It is one of the commonly used data formats in Web API.

Grammar:

json_encode(数组);

For example:

$arr = array('name'=>'小明','age'=>18,'gender'=>'male');
$str = json_encode($arr);

The result is:

"{"name":"小明","age":18,"gender":"male"}"

2. Convert string to array

  1. explode ()Function

explode() function can split a string into an array according to the specified delimiter.

Syntax:

explode(分隔符, 字符串);

For example, use the "," delimiter to split the string into an array:

$str = "apple,orange,banana";
$arr = explode(',', $str);

The result is:

array('apple','orange','banana')
  1. json_decode() function

json_decode() function can decode JSON format string into PHP array format.

Syntax:

json_decode(JSON字符串, 是否转换为关联数组);

By default, the json_decode() function returns a dummy object (stdClass object). You can set the second parameter to TRUE and an array will be returned.

For example:

$str = '{"name":"小明","age":18,"gender":"male"}';
$arr = json_decode($str, TRUE);

The result is:

array('name'=>'小明','age'=>18,'gender'=>'male')

Summary

This article introduces how to convert arrays to strings and strings to arrays in PHP method. Each method has its own characteristics and uses, and can be selected and used according to different needs. By mastering these methods, you can bring convenience and efficiency to PHP development work.

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