← Back to all snippets
PHP

Convert String to PHP Array and Array to String

Discover how to easily convert a delimited string into a PHP array using `explode()` and join array elements back into a string with `implode()` for data manipulation.

<?php
// Converting a string to an array using explode()
$csvString = "apple,banana,cherry,date";
$fruitsArray = explode(',', $csvString);

echo "Array from string:
";
print_r($fruitsArray);

// Converting an array to a string using implode()
$newString = implode(' | ', $fruitsArray);
echo "
String from array: " . $newString . "
";

// Example with a limit on explode()
$sentence = "This is a sample sentence";
$wordsLimited = explode(' ', $sentence, 3);
echo "
Explode with limit 3:
";
print_r($wordsLimited);
?>
How it works: `explode()` splits a string by a specified delimiter into an array of substrings. It can optionally take a limit parameter to control the number of elements in the resulting array. Conversely, `implode()` joins array elements into a single string, using a specified 'glue' string to separate the elements. These functions are fundamental for parsing and generating string data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs