You can put ',' instead of just ,.

Try this:

$arr = array('item1', 'item2', 'item3');
$str = "'" . implode("','", $arr) . "'";
echo $str;
Answer from Volkan Ulukut on Stack Overflow
🌐
PHP
php.net › manual › en › function.implode.php
PHP: implode - Manual
The array of strings to implode. Returns a string containing a string representation of all the array elements in the same order, with the separator string between each element. ... <?php $array = ['lastname', 'email', 'phone']; var_dump(implode(",", $array)); // string(20) "lastname,email,phone" // Empty string when using an empty array: var_dump(implode('hello', [])); // string(0) "" // The separator is optional: var_dump(implode(['a', 'b', 'c'])); // string(3) "abc" ?>
🌐
W3Schools
w3schools.com › php › func_string_implode.asp
PHP implode() Function
The implode() function returns a string from the elements of an array. Note: This function is binary-safe. ... <?php $arr = array('Hello','World!','Beautiful','Day!'); echo implode(" ",$arr)."<br>"; echo implode("+",$arr)."<br>"; echo ...
Discussions

php array implode explode with symbol - Stack Overflow
suppose he's trying to format the array to put in a sql statement with IN. implode with quotes is a solution. More on stackoverflow.com
🌐 stackoverflow.com
php - Using a callback in implode() - Stack Overflow
Instead, we first want to transform all of the items in an array using a function and pass the result of that into implode. This operation is most commonly called map. Luckily, PHP provides this function as, well, array_map. More on stackoverflow.com
🌐 stackoverflow.com
php - What is the difference between implode() & join() - Stack Overflow
What is the difference between implode() & join() as both work the same way. More on stackoverflow.com
🌐 stackoverflow.com
String concatenation vs array implode in PHP - Stack Overflow
Having used Java for a long time my standard method for creating long strings piece by piece was to add the elements to an array and then implode the array. $out[] = 'a'; $out[] = 'b'; echo implod... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Tinkerwell
tinkerwell.app › blog › how-to-use-implode-in-php
How to use implode() in PHP (with examples) - Tinkerwell
The implode() function in PHP is used to join together an array of strings into a single string. This function takes two arguments: the first is the glue, which is the string that will be placed between each array element, and the second is ...
🌐
freeCodeCamp
freecodecamp.org › news › php-implode-convert-array-to-string-with-join
PHP Implode – Convert Array to String with Join
October 6, 2022 - In PHP, the implode() function is a built-in function that takes an array and converts it to a string. implode() doesn’t modify the original array. It doesn’t matter whether the array is an indexed or associative array.
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-implode-function
PHP implode() Function - GeeksforGeeks
September 23, 2024 - The implode() is a built-in function in PHP and is used to join the elements of an array.
Find elsewhere
Top answer
1 of 5
32

Use array_map:

$final_string = implode(' | ', array_map(function($item) {
    return '<a href="' . $item['uri'] . '">' . $item['title'] . '</a>';
}, $values));

I trust you'll properly escape the values as HTML in your real code.


As to why this works and your code doesn't, you were passing a function as the second argument to implode. Frankly, that makes little sense: you can join a bunch of strings together, or maybe even a bunch of functions, but you can't join a single function together. It sounds strange, especially if you word it that way.

Instead, we first want to transform all of the items in an array using a function and pass the result of that into implode. This operation is most commonly called map. Luckily, PHP provides this function as, well, array_map. After we've transformed the items in the array, we can join the results.

2 of 5
5

It seems that you need to assign the function to a variable, and then pass it through to make it work.

$fn = function($values) {
    $return = array();
    foreach($values as $value)
        $return[] = '<a href="' . $value['uri'] . '">' . $value['title'] . '</a>';
    return $return;
};
$final_string(' | ', $fn($values));
echo $final_string;

I am not sure what the reason is, though, and will need to check it in a little more depth to be able to give you a proper reason.

You can see the code working here

EDIT : Converted this answer to a community wiki so that everyone can contribute here.

EDIT : Explanation by @kmfk

When you pass the closure directly to the implode method - which explicitly wants a second argument of type array, it essentially checks the instanceof - hence the invalid argument. The implode function does not expect mixed type and doesn't know to execute the closure to get an array.

When you first assign that function to a variable, it causes PHP to first evaluate that variable and it ends up passing the returned value from the function into implode.

In that case you're returning an array from the function and passing that into implode - that checks out.

That anonymous function would be instanceof Closure, and

Closure !== array
🌐
Koladechris
koladechris.com › blog › php-implode-and-explode
PHP Implode and Explode
Learn how PHP implode() concatenates arrays into strings, and how explode() splits strings into arrays
🌐
Medium
medium.com › @imhamad › deprecated-implode-function-in-php-27f23dd5593f
Deprecated implode function in php >8.x - Hamad - Medium
February 22, 2024 - In PHP, the implode function is used to join array elements with a string. if you’re facing the deprecated warning it suggests that you…
🌐
GitHub
gist.github.com › jimmygle › 2564610
PHP function to recursively implode multi-dimensional arrays. · GitHub
function implode_recur ($separator, $arrayvar){ $output = " "; foreach ($arrayvar as $av) if (is_array ($av)) $out .= implode_r ($separator, $av); // Recursive Use of the Array else $out .= $separator.$av; ... Okay have a good coding! ... I fixed and modified @kachmi's simpler answer a bit (added php7.4 types, added braces, renamed variables so it's working and added check if the separator is actually needed)
🌐
C# Corner
c-sharpcorner.com › UploadFile › 051e29 › implode-and-explode-function-in-php
Implode and Explode in PHP
July 5, 2021 - In this article, learn how to use PHP Implode and PHP Explode in an application. PHP Explode function breaks a string into an array. PHP Implode function returns a string from an array.
🌐
DEV Community
dev.to › sanurag › mastering-phps-implode-effortlessly-join-arrays-into-strings-1mej
Mastering PHP's implode(): Effortlessly Join Arrays into Strings - DEV Community
July 22, 2025 - $numbers = [1, 2, 3, 4, 5]; // Using comma separator echo implode(',', $numbers); // Output: 1,2,3,4,5 // Using pipe separator echo implode(' | ', $numbers); // Output: 1 | 2 | 3 | 4 | 5 // Using no separator echo implode('', $numbers); // Output: 12345
🌐
Phpmentoring
phpmentoring.org › blog › php-implode-function
PHP Implode() Function - Join Array Elements Into A String
The Implode() function is one of the best ways to convert PHP arrays of different types and multiple, one, or no elements to a string. The function takes an array as the first parameter and a string to serve as the glue that concatenates the ...
🌐
Afterhoursprogramming
afterhoursprogramming.com › tutorials › php › string-implode-and-explode
String Implode & Explode - PHP
Enough of blowing things apart. Let’s start putting them back together with the PHP implode function. The implode function essentially does the opposite of the explode function. You can take an array and join it together and make it into one string instead of an array.
🌐
Flexiple
flexiple.com › php › php-implode
PHP implode - Array to string - Flexiple
March 15, 2022 - We learnt that the implode() function returns a string from the elements of an array. The function accepts its parameters in any order. However, for consistency with the explode() function we must use the documented order of arguments.
Top answer
1 of 16
139

A long-liner that works with any number of items:

echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1)), 'strlen'));

Or, if you really prefer the verboseness:

$last  = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both  = array_filter(array_merge(array($first), $last), 'strlen');
echo join(' and ', $both);

The point is that this slicing, merging, filtering and joining handles all cases, including 0, 1 and 2 items, correctly without extra if..else statements. And it happens to be collapsible into a one-liner.

2 of 16
118

I'm not sure that a one liner is the most elegant solution to this problem.

I wrote this a while ago and drop it in as required:

/**
 * Join a string with a natural language conjunction at the end. 
 * https://gist.github.com/angry-dan/e01b8712d6538510dd9c
 */
function natural_language_join(array $list, $conjunction = 'and') {
  $last = array_pop($list);
  if ($list) {
    return implode(', ', $list) . ' ' . $conjunction . ' ' . $last;
  }
  return $last;
}

You don't have to use "and" as your join string, it's efficient and works with anything from 0 to an unlimited number of items:

// null
var_dump(natural_language_join(array()));
// string 'one'
var_dump(natural_language_join(array('one')));
// string 'one and two'
var_dump(natural_language_join(array('one', 'two')));
// string 'one, two and three'
var_dump(natural_language_join(array('one', 'two', 'three')));
// string 'one, two, three or four'
var_dump(natural_language_join(array('one', 'two', 'three', 'four'), 'or'));

It's easy to modify to include an Oxford comma if you want:

function natural_language_join( array $list, $conjunction = 'and' ) : string {
    $oxford_separator = count( $list ) == 2 ? ' ' : ', ';
    $last = array_pop( $list );

    if ( $list ) {
        return implode( ', ', $list ) . $oxford_separator . $conjunction . ' ' . $last;
    }

    return $last;
}
🌐
Codecademy
codecademy.com › docs › php › string functions › implode()
PHP | String Functions | implode() | Codecademy
May 27, 2023 - The example below uses the implode() function to create the sentence ‘I love learning with Codecademy’. The separator is a single space. <?php · $to_be_imploded = array('I','love','learning','with','Codecademy'); echo implode(' ',$to_be_imploded); ?> Copy to clipboard ·