How to split in PHP?

I want to split a string in PHP into two to separate two strings wherever there is a comma. For example let’s say we have a string this is, my string. I want to make this is and my string into two separated strings. Then I want to assign them into different variables so that I can use them separately. How can I do that?

You can use the explode() function to split strings at a specific separator. This is how it works.

$string = "this is, my string";
$value = explode(', ', $string);

This will return an array of the split strings this is and my string.

Adding to the answer provided by @Lakshmi, If you want to limit the number of output items, you can use a third parameter to limit the returned items as follows:

print_r(explode(', ', $str, -1));

For example:

$str = 'one, two, three, four';
print_r(explode(', ', $str, -1));

will output

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

If you use a positive value instead, it will return an array with a maximum of the number of elements (the last parameter) with the last element containing the rest of the strings.

For example:

$str = 'one, two, three, four';

print_r(explode(', ', $str, 2));

will return

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

I know that, the question doesn’t ask for this, but anyone in the future might find this helpful.