I have an array and I want to generate a message out of them. If I use join(', ', $response), I get file1.jpg, file2.jpg, file3.jpg. Is it possible to replace the last comma so the message would be file1.jpg, file2.jpg AND file3.jpg?

3 Answers

DoMajor7th On Best Solutions

This should work;




$arr=$response[1].' AND ' .$response[0];
for ($i=2; $i < count($response); $i++) { 
array_push($new, $arr);

echo join(", ",$new);
Joffrey Schmitz On

You can use array_slice to get all the elements in the array but the last one and make a special case for it :

function formatList($response)
    if(count($response) == 0)
        return '' ;
    if(count($response) == 1)
        return $response[0] ;
        return join(', ', array_slice($response, 0, count($response)-1)) . ' AND ' . end($response);
Zzaly Oreo On

substr_replace replace a portion of a string by position and length, strrpos find position of the last comma.

$response = ['file1.jpg', 'file2.jpg', 'file3.jpg'];
$out = join(', ', $response);
echo substr_replace($out, " AND", strrpos(($out), ','), 1);

https://www.php.net/manual/en/function.substr-replace.php https://www.php.net/manual/en/function.strrpos.php