php method to convert a string into an array: 1. Use the explode function to split a string into another string and return an array; 2. Use the str_split function to convert the string into an array.
The operating environment of this tutorial: Windows 7 system, PHP version 7.1. This method is suitable for all brands of computers.
Recommended: "PHP Video Tutorial"
explode — Use one string to split another string and return an array
<?php // 示例 1 $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 // 示例 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh"; list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data); echo $user; // foo echo $pass; // * ?>
Here if the character If the string does not have any symbols to split, you need to consider other methods
str_split - Convert the string into an array
<?php $str = "Hello Friend"; $arr1 = str_split($str); $arr2 = str_split($str, 3); print_r($arr1); print_r($arr2); ?>
Output result
Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => F [7] => r [8] => i [9] => e [10] => n [11] => d ) Array ( [0] => Hel [1] => lo [2] => Fri [3] => end )
If it is incompatible , the only way to consider is to break the string bit by bit,
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!