PHP convert string to array

后端 未结 6 1991
南方客
南方客 2020-12-10 12:54

How can I convert a string to an array? For instance, I have this string:

$str = \'abcdef\';

And I want to get:

array(6) {
         


        
相关标签:
6条回答
  • 2020-12-10 13:19

    Note that starting with php 5.5 you can refer to string characters by array indices, which in most cases prevents need for the solution(s) above.

    $str = 'abdefg';
    echo $str[4]; // output: f
    
    0 讨论(0)
  • 2020-12-10 13:22

    Other solution:

    $string = 'abcdef';
    
    $arr = [];
    
    for($i=0;$i<strlen($string);$i++){
        $arr[] = substr($string,$i,1);
    }
    
    0 讨论(0)
  • 2020-12-10 13:23

    Use str_split http://www.php.net/manual/en/function.str-split.php

    0 讨论(0)
  • 2020-12-10 13:34

    You can loop through your string and return each character or a set of characters using substr in php. Below is a simple loop.

    $str = 'abcdef';
    $arr = Array();
    
    for($i=0;$i<strlen($str);$i++){
        $arr[$i] = substr($str,$i,1);
    }
    
    /*
    OUTPUT:
    $arr[0] = 'a';
    $arr[1] = 'b';
    $arr[2] = 'c';
    $arr[3] = 'd';
    $arr[4] = 'e';
    $arr[5] = 'f';
    */
    
    0 讨论(0)
  • 2020-12-10 13:37

    Every String is an Array in PHP

    So simply do

    $str = 'abcdef';
    echo $str[0].$str[1].$str[2]; // -> abc
    
    0 讨论(0)
  • 2020-12-10 13:39
    <?php
    
    $str = "Hello Friend";
    
    $arr1 = str_split($str);
    $arr2 = str_split($str, 3);
    
    print_r($arr1);
    echo "<br/>";
    print_r($arr2);
    
    ?>
    

    more info !!

    0 讨论(0)
提交回复
热议问题