Repeat Loop

2

As I enter a "," between the items in While and in the last item I put a "e" plus a "." . Remembering that my array will load according to the data in the database.

I need it written like this:

Pera , Uva , Melao and Morango .

vetor = new Array ("Pera", "Uva", "Melao", "Morango");
    
asked by anonymous 04.05.2015 / 13:32

3 answers

6

By your example I get the feeling that you are using JavaScript ... because you lack $ in variables and JavaScript uses new Array() . In PHP, only array() is used. I put together both solutions.

PHP

You can remove the last element, join the others with , and then put it back with simple concatenation.

$vetor = array("Pera", "Uva", "Melao", "Morango");
$ultimo = array_pop($vetor);
$string = implode(', ', $vetor);
$string.= " e {$ultimo}.";

Example: link

JavaScript

var vetor = new Array("Pera", "Uva", "Melao", "Morango");
var ultimo = vetor.pop();
var string = vetor.join(', ');
string += ' e ' + ultimo + '.';

jsFiddle: link

    
04.05.2015 / 13:46
3

To insert a , between elements use implode like this:

$separado = implode(",", $vetor);

find the last comma:

$pos = strripos($separado, ',');

put e :

$string = substr_replace($separado, ' e ', $pos, 1);

put a dot at the end:

$string .= '.';

DEMO

    
04.05.2015 / 13:35
1

I hope to help with my answer, as I have tried to find another way to do so. Here goes ...

<?php

$vetor = array("Pera", "Uva", "Melao", "Morango");

$final = $vetor[0];

for ($i = 1; $i < count($vetor) - 1; $i++)
{
    $final.= ', '.$vetor[$i];
}

$final.= ' e '.end($vetor).'.';

echo $final;
    
04.05.2015 / 14:06