can I 'explode' every character in a string?

Discussion in 'PHP' started by rhythmiccycle, Nov 1, 2007.

  1. #1
    I know how to use the explode function. But i want to explode every character in a string (with out using a separator). for example, make:

    "some string"

    into an array:

    Array
    (
    [0] => s
    [1] => o
    [2] => m
    [3] => e
    [4] =>
    [5] => s
    [6] => t
    [7] => r
    [8] => i
    [9] => n
    [10] => g
    )

    I want to explode everything (not just at the separator).

    how can this be done??
     
    rhythmiccycle, Nov 1, 2007 IP
  2. brendandonhue

    brendandonhue Peon

    Messages:
    45
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    This is already done. $string[0] is the first character, $string[1] is the 2nd character, etc.
     
    brendandonhue, Nov 1, 2007 IP
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    brendandonhue's answer is correct, but you can also use something like this:

    
    
    $string = 'your string';
    
    for($i=0;$i< strlen($string);$i++){
    
    $array[] = substr($string, $i , 1);
    
    }
    
    
    PHP:
     
    jestep, Nov 1, 2007 IP
  4. bobb1589

    bobb1589 Peon

    Messages:
    289
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #4
    what exactly do you need to do this for? maybe someone here can think of a better way of doing it if you explain what you need it for?
     
    bobb1589, Nov 1, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    nico_swd, Nov 2, 2007 IP
  6. brendandonhue

    brendandonhue Peon

    Messages:
    45
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #6
    There's no reason to reinvent the wheel (and use the overhead of a loop or the regular expression engine.) Accessing characters in a string like array elements is already built in to PHP.
     
    brendandonhue, Nov 2, 2007 IP
  7. TecBrat

    TecBrat Member

    Messages:
    31
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #7
    I was going to answer the same way brendandonhue did, but I checked out str_split that nico_swd posted, and it does exactly this, and lets you choose how many characters to put in each element.
     
    TecBrat, May 10, 2009 IP