Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP to form string like "A, B, C, and D" from array values

Given the following array:

Array
(
    [143] => Car #1
    [144] => Car #2
    [145] => Car #3
)

I am currently using this

implode(', ', array_values($car_names))

to generate a string like

Car #1, Car #2, Car #3

I would like to actually get something like

Car #1, Car #2 and Car #3

The idea would be to insert " and " between the two last elements of the array.

If the array happens to contain two key/value pairs (eg, user has 2 cars), there would be no commas.

Car #1 and Car #2

And if the array contains one key/value (eg, user has 1 car)

Car #1

Any suggestion how to get this done? I tried using array_splice but I'm not sure that's the way to go (ie, inserting a new element into the array).

Thanks for helping!

like image 311
pepe Avatar asked Dec 13 '22 12:12

pepe


2 Answers

$last = array_pop($car_names);
echo implode(', ', $car_names) . ' AND ' . $last;
like image 70
David Chan Avatar answered Dec 15 '22 00:12

David Chan


I think you probably want something like this, using array_pop to get the last element off the end of the array. You can then implode the rest of the array, and add the last element in a custom fashion:

$last_value = array_pop($car_names);
$output = implode(', ', array_values($car_names));
$output .= ($output ? ' and ' : '') . $last_value;

Edit: added conditional to check if the array had only one element.

like image 44
lonesomeday Avatar answered Dec 15 '22 02:12

lonesomeday