implode()
21st January 2021
0 Comments
Programming Language
PHP [Versions: 4, 5, 7, 8]
Syntax
Typical Usage
Converting array to strings.
Accepted Parameters
- separator (string) (Required): The string to be used as a separator. May be an empty string.
- array (array) (Required): The array whose elements should be concatenated into a string.
Return Value(s)
Returns a string of each array element separated by the separator.Examples
Example 1
<?php
$pets_array = ['dogs', 'cats', 'birds', 'fish'];
$pets = implode(', ', $pets_array);
print_r('Her pets include ' . $pets . '.');
The above will output: “Her pets include dogs, cats, birds, fish.”. We can make this a bit better with array_pop() in the next example;
Example 2: Use implode() and array_pop() to Separate An Array’s Last Element with “and”
<?php
$pets_array = ['dogs', 'cats', 'birds', 'fish'];
if( count($pets_array) ) {
// Remove the last element from the array and store it as last_pet
$last_pet = array_pop($pets_array);
$string = 'Her pets include ';
// Since we remove the last element with array_pop(), we need to check that the original array still has something
if( count($pets_array)) {
$string .= implode(', ', $pets_array) . ' and ' . $last_pet . '.';
}
// Else we just return that popped element
else {
$string .= $last_pet . '.';
}
}
else {
$string = 'She has no pets.';
}
$pets = implode(', ', $pets_array);
print_r($string);
With array_pop(), we can add “and” (or “or”) to the last element. The above will output: “Her pets include dogs, cats, birds and fish.”
Used In Projects
Similar Functions in Other Languages
- Javascript: array.join()
Was This Helpful?
If this post has helped you, please let me know. Your feedback will be highly appreciated and will help me build better content.