I want to separate an array with comma and word.
This is the code that i make:
$array = array( 'user1', 'user2', 'user3', 'user4', 'user5' );
$last = array_pop( $array );
$string = count( $array ) ? implode( ", ", $array ) . " and " . $last : $last;
printf( 'Authors: %s', $string );
My code print this:
Authors: user1, user2, user3, user4 and user5
I successfully made a code to implode the array with a comma and search for the last key and separate it with a word 'and'.
But that's what I want but I failed after more than 2 days of work on this:
Authors: user1, user2, and user3 and 2 others.
There are several ways to do it, one simple way :
First you should get the numbers of elements in your array to see if it's more than 3 or not.
Then if it's more than 3 , you can make your string:
If you want to know more about PHP arrays you can use this link , a quick tutorial
Or the documentation
I suggest you to think your problem as a function that you can Unit-Test so it becomes easier to build and you can flexibilize your solution.
array_pop
array_slice
to get the first chunk from the "take N" argument.Here an example of how it could be.
Will output:
Working example here
Alternative
An alternative for handling special cases and printing the last item value.
Will print:
Feel free to adjust to your needs.
Working code example
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 aswitch-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)
Output:
p.s. A more compact version of the same handling:
Code: (Demo)
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)
Here's one way to do it:
Start by imploding the first two array elements. (
array_splice
will remove them from$array
.)Add the third one if it's there. (
array_shift
will remove it from$array
too.)Count the rest and add them, if any are left.