Implode an Array With ", " and Add "And " Before the Last Item

Implode an array with , and add and before the last item

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.

PHP implode explode first and last array value

This with name pieces separated with a space, and works with a single name piece like Andre:

<?php
$fullname = 'Andre Filipe da Costa Ferreira';
$namepieces = explode(' ', $fullname);
$n = count($namepieces);
if($n > 1) {
$flname = implode(' ', array($namepieces[0], $namepieces[$n-1]));
} else {
$flname = $namepieces[0];
}
echo "Welcome " . $flname;
//
?>

This gets:

Welcome Andre Ferreira

implode() string, but also append the glue at the end

This was an answer from my friend that seemed to provide the simplest solution using a foreach.

$array = array ('1112223333', '4445556666', '7778889999');

// Loop over array and add "@att.com" to the end of the phone numbers
foreach ($array as $index => &$phone_number) {
$array[$index] = $phone_number . '@att.com';
}

// join array with a comma
$attusers = implode(',',$array);

print($attusers);

Comma separated list from array with and before last element

Try array_pop() to get the last element, then array_push to modify and push the element back:

http://php.net/manual/en/function.array-pop.php

Something like

$last_element = array_pop($number_list);
array_push($number_list, 'and '.$last_element);

Then you can do your implode:

$comma_list = implode(', ', $number_list);

Adding a character before last word in PHP array

implode cannot do this directly, but it's not that difficult:

switch (count($credits)) {
case 0:
$result = '';
break;
case 1:
$result = reset($credits);
break;
default:
$last = array_pop($credits); // warning: this modifies the array!
$result = implode(', ', $credits).' & '.$last;
break;
}

How can I devote different separator for last item?

You can use foreach and build your own implode();

function implode_last( $glue, $gluelast, $array ){
$string = '';
foreach( $array as $key => $val ){
if( $key == ( count( $array ) - 1 ) ){
$string .= $val.$gluelast;
}
else{
$string .= $val.$glue;
}
}
//cut the last glue at the end
return substr( $string, 0, (-strlen( $glue )));
}

$array = array ( 1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four' );

echo implode_last( ', ', ' and ', $array );

If your Array starts with Index 0 you have to set count( $array )-2.

Separate an array with comma and string PHP

While I always look for the clever calculated process for handling a task like this, I'll offer a much more pedestrian alternative. (For the record, I hate writing a battery of if-elseif-else conditions almost as much as I hate the verbosity of a switch-case block.) For this narrow task, I am electing to abandon my favored array functions and conditionally print the values with their customized delimiters.

While this solution is probably least scalable on the page, it is likely to be the easiest to comprehend (relate the code to its generated output). If this is about "likes" or something, I don't really see a large demand for scalability -- but I could be wrong.

Pay close attention to the 2-count case. My solution delimits the elements with and instead of , which seems more English/human appropriate.

Code: (Demo)

$arrays[] = array();
$arrays[] = array('user1');
$arrays[] = array('user1', 'user2');
$arrays[] = array('user1', 'user2', 'user3');
$arrays[] = array('user1', 'user2', 'user3', 'user4');
$arrays[] = array('user1', 'user2', 'user3', 'user4', 'user5');

foreach ($arrays as $i => $array) {
echo "TEST $i: ";
if (!$count = sizeof($array)) {
echo "nobody";
} elseif ($count == 1) {
echo $array[0];
} elseif ($count == 2) {
echo "{$array[0]} and {$array[1]}";
} elseif ($count == 3) {
echo "{$array[0]}, {$array[1]}, and {$array[2]}";
} else {
echo "{$array[0]}, {$array[1]}, {$array[2]}, and " , $count - 3, " other" , ($count != 4 ? 's' : '');
}
echo "\n---\n";
}

Output:

TEST 0: nobody
---
TEST 1: user1
---
TEST 2: user1 and user2
---
TEST 3: user1, user2, and user3
---
TEST 4: user1, user2, user3, and 1 other
---
TEST 5: user1, user2, user3, and 2 others
---

p.s. A more compact version of the same handling:

Code: (Demo)

if (!$count = sizeof($array)) {
echo "nobody";
} elseif ($count < 3) {
echo implode(' and ', $array);
} else{
echo "{$array[0]}, {$array[1]}";
if ($count == 3) {
echo ", and {$array[2]}";
} else {
echo ", {$array[2]}, and " , $count - 3, " other" , ($count != 4 ? 's' : '');
}
}

And finally, here's an approach that "doctors up" the array and prepends and to the final element. I think anyway you spin this task, there's going to be a degree of convolution.

Code: (Demo)

$count = sizeof($array);
if ($count < 3) {
echo implode(' and ', $array);
} else {
if ($count == 3) {
$array[2] = "and {$array[2]}";
} else {
$more = $count - 3;
array_splice($array, 3, $more, ["and $more other" . ($more > 1 ? 's' : '')]);
}
echo implode(', ', $array);
}

During a CodeReview, I realized a "pop-prepend-push" technique: https://codereview.stackexchange.com/a/255554/141885


From PHP8, match() is also available. An implementation might look like this: (Demo)

$count = count($array);
echo match ($count) {
0 => 'nobody',
1 => $array[0],
2 => implode(' and ', $array),
3 => "{$array[0]}, {$array[1]}, and {$array[2]}",
default => "{$array[0]}, {$array[1]}, {$array[2]}, and " . $count - 3 . " other" . ($count != 4 ? 's' : '')
};

Move last array string to end of second last array string

Remove tow last items by array_splice and add implode of them

$temp = array_splice($array,-2); 
$result = array_merge($array, (array) implode(',', $temp));

demo

As @Nick mentioned, you can do it by

$temp = array_splice($array,-2); 
$array[] = implode(',', $temp);


Related Topics



Leave a reply



Submit