Loop

Asked

Viewed 124 times

2

How do I insert a "," among the items in While and in the last item I put a "e" one more ".". 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");
  • 1

    It seems the same logic question

3 answers

6


By your example I get the feeling that you are using Javascript... because you lack $ variables and Javascript uses new Array(). In PHP it is only used array(). I joined both solutions.

PHP

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

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

Example: https://ideone.com/sjfjX2


Javascript

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

jsFiddle: http://jsfiddle.net/Lj5vktd7/

  • 1

    I tried to edit, but I’m not getting it. I missed a space on ',' and in the 'e '.$ultimo.'.'; generating Pera,Uva,Melaoe Morango.

  • 1

    I suggest using $string.= " e {$ultimo}.";

  • @Thank you Guilhermelautert. I added your suggestion! I had put it right in Ideone but here still lacked the space.

3

to insert a , between the elements use a implode in this way:

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

find the last comma:

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

put the e:

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

put a point to the end:

$string .= '.';

DEMO

1

I hope to help with my answer because I have tried to find another way to do so. Here it comes...

<?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;
  • apart from the fact that you are inserting twice Morango this ok. change to count($vetor) - 1, that solves.

  • Done... Thanks @Guilherme Lautert, it was inattentive!

Browser other questions tagged

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