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
0
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] ;
else
return join(', ', array_slice($response, 0, count($response)-1)) . ' AND ' . end($response);
}
0

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
This should work;