0

I could do that using just the if and elseifmanually, but it doesn't works if I use an array result to separate by comma...

So, this is what I'm trying to do:

on DB a member has 3 languages in this format: english, portuguese, spanish

how to print that in this format: english, portuguese and spanish?

This is how the result is print:

foreach($acc_languages as $list){
$languages = $list['lang'];
}

there is some "list format" to add a comma to separate values with an "and" before the last?

user3050478
  • 274
  • 2
  • 19
  • 1
    consider what would happen if the list had 1 item only. –  Feb 27 '14 at 02:57
  • I'm working on it, I'm creating an array with the $acc_languages result and checking if there is just one value on array, if it have more than 1 value, then I use his code... I think it's gonna work :) – user3050478 Feb 27 '14 at 03:11

4 Answers4

3

You could use a combination of implode and preg_replace:

$languages = implode(', ', $acc_languages);
$languages = preg_replace('/, ([^,]*)$/',' and $1',$languages);

This creates commas to separate them then changes the last to an and without a comma.

This also assumes that no languages have a comma in them.

Anonymous
  • 11,347
  • 6
  • 32
  • 56
3

Grab the last element out of the array, combine the other items, then add the last one after 'and':

$lastLang = array_pop($acc_languages);
$languages = implode(', ',$acc_languages);
$languages .= ' and '.$lastLang;
Mark Parnell
  • 9,125
  • 9
  • 29
  • 36
2

Get the position of the last comma and then replace it with the " and" string.

<?php

$list = "english, spanish, portugese";

$list = substr_replace($list, " and", strrpos($list, ","), 1);

echo $list;  //echos english, spanish and portugese

?>

Hope that helps!!

Crackertastic
  • 4,893
  • 2
  • 28
  • 37
0

really fast:

foreach($acc_languages as $list){
    $languages = (($pos = strrpos($list['lang'],","))!==FALSE ? 
                   substr_replace($list['lang']," and",$pos,1) : $list['lang']);
}