Home  >  Article  >  Backend Development  >  How to convert a php string into a two-dimensional character array

How to convert a php string into a two-dimensional character array

PHPz
PHPzOriginal
2023-04-18 10:20:43537browse

In PHP, there are many ways we can convert a string into a two-dimensional array of characters. The following are two of the methods:

Method 1: Use the str_split function

The str_split function in PHP can split a string into a character array. We can use this function to convert a string into a two-dimensional character array.

Sample code:

<?php
$str = "hello world";
$chars = str_split($str);

//将字符数组转化为二维数组
$charArr = array();
for($i=0;$i<count($chars);$i++){
    $charArr[$i][0] = $chars[$i];
}

print_r($charArr);
?>

Run result:

Array
(
    [0] => Array
        (
            [0] => h
        )

    [1] => Array
        (
            [0] => e
        )

    [2] => Array
        (
            [0] => l
        )

    [3] => Array
        (
            [0] => l
        )

    [4] => Array
        (
            [0] => o
        )

    [5] => Array
        (
            [0] =>  
        )

    [6] => Array
        (
            [0] => w
        )

    [7] => Array
        (
            [0] => o
        )

    [8] => Array
        (
            [0] => r
        )

    [9] => Array
        (
            [0] => l
        )

    [10] => Array
        (
            [0] => d
        )

)

Method 2: Use the mb_str_split function

In addition to the str_split function, PHP also provides the mb_str_split function, Converts a multibyte string to a character array.

Sample code:

<?php
$str = "你好,世界!";
$chars = mb_str_split($str);

//将字符数组转化为二维数组
$charArr = array();
for($i=0;$i<count($chars);$i++){
    $charArr[$i][0] = $chars[$i];
}

print_r($charArr);
?>

Running result:

Array
(
    [0] => Array
        (
            [0] => 你
        )

    [1] => Array
        (
            [0] => 好
        )

    [2] => Array
        (
            [0] => ,
        )

    [3] => Array
        (
            [0] => 世
        )

    [4] => Array
        (
            [0] => 界
        )

    [5] => Array
        (
            [0] => !
        )

)

Finally, no matter which method you use, don’t forget to use a loop to convert the character array into a two-dimensional character array . In this way, we can easily process and operate strings.

The above is the detailed content of How to convert a php string into a two-dimensional character array. 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