Convert String to Array in PHP

- 1 minute read

This PHP snippet, which splits a string by a given separator into an array, is extremely handy:

function toArray($str, $separator) {
    return explode($str, $separator);
}

The best part is that it’s basically a one-liner!

Here’s how you could use it to split a string by its commas into an array:

$str = 'red,yellow,blue';
$arr = toArray($str, ',');

After the above snippet has run, $arr will return an array: ["red", "yellow", "blue"].

Here is one more example that uses semicolons instead of commas:

$str = 'apple;orange;banana';
$arr = toArray($str, ';');

And after that snippet has run, $arr will return an array: ["apple", "orange", "banana"].

By the way, if you wanted to make the toArray function a bit more failproof, you could first check if $str contains $separator, and whether $str is a string at all:

function toArray($str, $separator) {
    if (!is_string($str)) { // Check if $str is a string
        return false;
    }
    if (!str_contains($str, $separator)) { // Check if $str contains $separator
        return false;
    }
    return explode($str, $separator);
}

If that criteria is not met, this modified toArray function will return false.

Link to this section Conclusion

I hope you found this useful. It’s especially great when working with CSV data.

Happy string splitting!