How to convert string to array in php

藏色散人
Release: 2023-03-07 22:46:01
Original
4748 people have browsed it

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.

How to convert string to array in php

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; // *
 
?>
Copy after login

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

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

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!

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!