PHP

Convert Between PHP Arrays and Delimited Strings (`implode`, `explode`)

Master implode() to combine array elements into a single string with a specified delimiter, and explode() to split a delimited string back into an array in PHP.

<?php
$fruits = ['apple', 'banana', 'cherry'];

// Convert an array to a comma-separated string
$fruitString = implode(', ', $fruits);
echo "Array to String: " . $fruitString . "
"; // Result: "apple, banana, cherry"

// Convert a comma-separated string back to an array
$newFruitsArray = explode(', ', $fruitString);
echo "String to Array: ";
print_r($newFruitsArray); // Result: ['apple', 'banana', 'cherry']

$csvData = "Name,Age,City
John,30,New York
Jane,25,London";

// Split CSV string into lines
$lines = explode("
", $csvData);
print_r($lines);

// Process each line
foreach ($lines as $line) {
    $parts = explode(',', $line);
    // Do something with $parts, e.g., create an associative array
    // echo "Processed: " . implode(' | ', $parts) . "
";
}

// Using different delimiters
$path = "usr/local/bin";
$pathParts = explode('/', $path);
print_r($pathParts); // Result: ['', 'usr', 'local', 'bin']
?>
How it works: The implode() and explode() functions are essential for interconverting between arrays and strings in PHP. implode() takes an array of strings and joins them into a single string, using a specified delimiter between each element. Conversely, explode() takes a string and a delimiter, splitting the string into an array of substrings wherever the delimiter is found. These functions are frequently used for tasks like generating CSV data, parsing URLs, or handling log entries.

Need help integrating this into your project?

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

Hire DigitalCodeLabs