Convert a String into an Array of Characters

2020-01-28 08:03发布

In PHP, how do i convert:

$result = abdcef;

into an array that's:

$result[0] = a;
$result[1] = b;
$result[2] = c;
$result[3] = d;

7条回答
家丑人穷心不美
2楼-- · 2020-01-28 08:36

You will want to use str_split().

$result = str_split('abcdef');

http://us2.php.net/manual/en/function.str-split.php

查看更多
SAY GOODBYE
3楼-- · 2020-01-28 08:41

best you should go for "str_split()", if there is need to manual Or basic programming,

    $string = "abcdef";
    $resultArr = [];
    $strLength = strlen($string);
    for ($i = 0; $i < $strLength; $i++) {
        $resultArr[$i] = $string[$i];
    }
    print_r($resultArr);

Output:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)
查看更多
做个烂人
4楼-- · 2020-01-28 08:44

You can use the str_split() function

$array = str_split($string);

foreach ($array as $p){

    echo $p . "<br />";
}
查看更多
祖国的老花朵
5楼-- · 2020-01-28 08:44
$result = "abcdef";
$result = str_split($result);

There is also an optional parameter on the str_split function to split into chunks of x characters.

查看更多
小情绪 Triste *
6楼-- · 2020-01-28 08:49

Don't know if you're aware of this already, but you may not need to do anything (depending on what you're trying to do).

$string = "abcdef";
echo $string[1];
//Outputs "b"

So you can access it like an array without any faffing if you just need something simple.

查看更多
Deceive 欺骗
7楼-- · 2020-01-28 08:50

With the help of str_split function, you will do it.

Like below::

<?php 
$result = str_split('abcdef',1);
echo "<pre>";
print_r($result);
?>
查看更多
登录 后发表回答