← Back to Chapters

PHP explode() & implode()

? PHP explode() & implode()

? Quick Overview

PHP provides two powerful functions, explode() and implode(), that work with strings and arrays. explode() converts a string into an array, while implode() converts an array back into a string.

? Key Concepts

  • explode() splits a string into an array using a delimiter.
  • implode() joins array elements into a string using a separator.

? Syntax / Theory

  • explode(delimiter, string)
  • implode(separator, array)

? Code Example: explode()

? View Code Example
// Split a comma-separated string into an array
<?php
$string = "apple,banana,cherry";
$array = explode(",", $string);
print_r($array);
?>

? Explanation

The string is split wherever a comma appears, resulting in an array containing individual fruit names.

? Code Example: implode()

? View Code Example
// Join array values into a single string
<?php
$array = array("apple", "banana", "cherry");
$string = implode(", ", $array);
echo $string;
?>

? Live Output / Explanation

Output: apple, banana, cherry

The array values are joined using a comma and space.

? Interactive Concept

Think of explode() as breaking a sentence into words, and implode() as rebuilding the sentence using custom spacing.

? Use Cases

  • Processing CSV or form input data
  • Converting database values to readable text
  • String manipulation for APIs and URLs

✅ Tips & Best Practices

  • Always validate strings before exploding.
  • Choose clear separators for readability.
  • Use implode() for generating display strings.

? Try It Yourself

  • Split a sentence into words using spaces.
  • Join numbers with a custom separator like |.
  • Create a function that explodes, modifies, and implodes data.