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

How to convert string to array in php

青灯夜游
青灯夜游Original
2021-09-18 19:42:144290browse

Conversion method: 1. Use the explode() function to split a string into several substrings according to the delimiter, and then combine these substrings into an array and return it. The syntax "explode(delimiter, String)"; 2. Use str_split() function, syntax "str_split(string)".

How to convert string to array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php converts string to array (Array) Method 1: Use the explode() function

explode() function can split a string based on the string delimiter, that is, it splits a string into several sub-strings based on the delimiter. string, then combine these substrings into an array and return it. The syntax format is as follows:

explode($delimiter, $string [, $limit])

The parameter description is as follows:

  • $delimiter: the delimiter character used to split the string;
  • $string: required Split string;
  • $limit: optional parameter, which can be empty, specifies the number of array elements to be returned;
    • If $limit is not empty and is a positive number, the returned The array contains at most $limit elements, and the last element contains the remainder of $string;
    • If $limit is not empty and is a negative number, all elements except the last $limit elements are returned;
    • If $limit is 0, it will be treated as 1;
    • If $limit is empty, it means returning all array elements.

Example:

<?php
header("Content-type:text/html;charset=utf-8");
$str = "PHP中文网,https://www.php.cn/";
$arr = explode(&#39;,&#39;, $str);
var_dump($arr);
$arr = explode(&#39;,&#39;, $str, 1);
var_dump($arr);
?>

Output result:

How to convert string to array in php

php will Method 2 to convert a string into an array (array): Use the str_split() function

str_split() function to split the string into an array.

Syntax

str_split(string,length)

The parameter description is as follows:

  • string Required. Specifies the string to be split.

  • #length Optional. Specifies the length of each array element. The default is 1.

Example:

<?php
header("Content-type:text/html;charset=utf-8");
$str = "Hello";
$arr = str_split($str);
var_dump($arr);
$arr = str_split($str,2);
var_dump($arr);
?>

Output result:

How to convert string to array in php

Recommended learning: "PHP Video Tutorial

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