PHP
Convert Strings to Arrays and Arrays to Strings in PHP
Master the `explode()` and `implode()` functions to seamlessly convert delimited strings into arrays and arrays back into strings, crucial for data parsing and serialization.
<?php
// 1. Converting a string to an array using explode()
$tagString = "php,javascript,html,css";
$tagsArray = explode(",", $tagString);
echo "Original string: " . $tagString . "
";
echo "Converted array: ";
print_r($tagsArray);
/*
Output:
Original string: php,javascript,html,css
Converted array: Array
(
[0] => php
[1] => javascript
[2] => html
[3] => css
)
*/
echo "
--------------------
";
// 2. Converting an array to a string using implode()
$fruitsArray = ['apple', 'banana', 'orange'];
$fruitsString = implode(" | ", $fruitsArray);
echo "Original array: ";
print_r($fruitsArray);
echo "Converted string: " . $fruitsString . "
";
/*
Output:
Original array: Array
(
[0] => apple
[1] => banana
[2] => orange
)
Converted string: apple | banana | orange
*/
?>
How it works: `explode()` splits a string by a specified delimiter into an indexed array of substrings. Conversely, `implode()` joins array elements into a single string using a specified delimiter. These functions are fundamental for handling common data formats like CSV strings, tag lists, or constructing messages from array data.