Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to convert a string to an array

Short answer

explode() splits a string by a separator:

<?php
 
print_r(explode(', ', 'red, green, blue'));

Output:

Array
(
    [0] => red
    [1] => green
    [2] => blue
)

By characters

mb_str_split() returns the individual characters:

<?php
 
print_r(mb_str_split('код'));

Output:

Array
(
    [0] => к
    [1] => о
    [2] => д
)

By words

When words may be separated by several spaces, split the string with a regular expression:

<?php
 
print_r(preg_split('/\s+/', trim('  one   two three ')));

Output:

Array
(
    [0] => one
    [1] => two
    [2] => three
)

Functions used in this recipe

  • explode — Splits a string into an array by a separator.
  • implode — Joins array elements into a string.

Thanks for reading!

Donate to the site — we work hard for you.