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!
$last = array_pop($car_names);
echo implode(', ', $car_names) . ' AND ' . $last;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With