how to separate array values by "," and "and"

Asked

Viewed 1,842 times

1

Hello I have an array and need to print it on the screen separated by , and and ex..

<select name="quitacao[um]"class="large m-wrap" data-trigger="hover"  required="" > 
<select name="quitacao[dois]"class="large m-wrap" data-trigger="hover" required="" >

and so it goes

then I will have a quitacao array on the next screen

if I do this

implode(",",$quitacao);

I’ll be able to separate everything by comma but I need the last one to be with E

ex. January, February, March and November

2 answers

3

Take all elements of the array down to the penultimate of them and concatenate them with a comma; then concatenate the latter with an "and":

function concatena($meses)
{
    $string  = implode(', ', array_slice($meses, 0, -1));
    $string .= ' e ' . $meses[count($meses)-1];

    return $string;
}
  • 1

    Obrigado Rodrigo

  • 2

    In that case, I think your answer is better in cases where the array cannot be modified. Because in @Danielomine’s reply, array would lose the last element because of array_pop, working on the reference of array, instead of returning the array;

  • truth. Well noted @Wallacemaxters. I made an edit by adding a simple hint for this case where you need to use the entire array.

3

$arr = ['janeiro', 'fevereiro', 'março', 'abril', 'maio'];
$l = array_pop($arr);
echo implode( ', ', $arr ) . ' e ' . $l;

The function array_pop() remove the last element of the array and return its value.

The variable $l receives the value, so you can use it in the concatenation.

In case you need to use the array in its original form, just return the value removed by the function array_pop().

$arr[] = $l;
  • 1

    Thanks daniel

  • In fact, if you put this all within a function, array_pop will only work on the variable of array in the context of the function (of course, if you declare the parameter without the reference).

  • What’s that got to do with it? rsrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.