Turn a string into an array in PHP


Ah, PHP and string manipulations, good ol’ stuff! To turn a comma-separated string into an array in PHP, you can use the explode() function. This function splits a string by a string separator (in our case, a comma) and returns an array.

Here’s a quick example:

$commaSeparatedString = "apple,banana,orange";
$array = explode(",", $commaSeparatedString);

print_r($array);

This will output:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

And just like that, you’ve got yourself an array from a comma-separated string. Easy-peasy, right?

Check for Array

You might also want to ensure the variable is a string and not an array before turning it into an array. This ternary operator will check to see if it’s an array. If it is, it just passes it along. If not, it will then use the explode() function.

$commaSeparatedString   = ( is_array( $commaSeparatedString ) ) ? $commaSeparatedString : explode( ',', $commaSeparatedString );