how to add "commas" and the word "and" before the last entry

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
melchor_06
Forum Newbie
Posts: 13
Joined: Wed Feb 11, 2009 3:58 am

how to add "commas" and the word "and" before the last entry

Post by melchor_06 »

i hope someone could help me. I'm new to php.

this is my code:

Code: Select all

 
<?php           
function ImplodeProper($value, $lastConnector = 'and')
 
{
  if( !is_array($value) or count($value) == 0) return '';
  $last = array_pop($value);
  if(count($value))
    return implode(', ',$value).", $lastConnector $last";
  else
    return $last; 
}
 foreach ($P1_languages as $value) 
 echo ImplodeProper(array($value['language'])) ;
?>
and the output was : englishchinesefrench

rather than english, chinese, and french

how can i do this?
is it right to use implode?

thanks in advance.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: how to add "commas" and the word "and" before the last entry

Post by requinix »

Build an array of just the languages. Nothing else.

Code: Select all

$example = array("english", "chinese", "french");
If there's only one item in the array then just use it. If there's two then take the first, add the connector, and add the last.
If there's three or more then add the connector to the last item in the array and implode (with a comma as the separator).

Code: Select all

// incomplete
$example = array("english", "chinese", "french");
$count = count($example);
 
if ($count == 0) {
} else if ($count == 1) {
} else if ($count == 2) {
} else if ($count >= 3) {
    $last = array_pop($example);
    $last = "and " . $last;
    array_push($example, $last);
    $list = implode(", ", $example);
}
melchor_06
Forum Newbie
Posts: 13
Joined: Wed Feb 11, 2009 3:58 am

Re: how to add "commas" and the word "and" before the last entry

Post by melchor_06 »

thanks tasairis...

but the thing is the data will come from a database.

for example the language table which one user can speak many languages (multiple inputs)

that explains the

Code: Select all

foreach ($P1_languages as $value)
and the

Code: Select all

echo $value['language']
how can i implement this to your solution which is efficient and correct from a given array point of view.

thanks again tasairis...
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: how to add "commas" and the word "and" before the last entry

Post by onion2k »

Just for a laugh I figured I'd write something to do this with a single line of code.

Code: Select all

<?php
 
    $words = array("English","French","Chinese","Japanese");
 
    echo implode("", array_map(create_function('$w,$i,$t', 'return $w.(($i+1<$t)?", ":((($i+1==$t))?" and ":""));'), $words, range(1,count($words)), array_fill(0, count($words), count($words))));
 
I am NOT recommending you do this. It's bad, unreadable, nasty code. I just have a twisted idea of fun.
melchor_06
Forum Newbie
Posts: 13
Joined: Wed Feb 11, 2009 3:58 am

Re: how to add "commas" and the word "and" before the last entry

Post by melchor_06 »

i figured it out. by this:

Code: Select all

 
<?php                                                                           
 $string = '';                          
 i = 0;
 $total = count($P1_language);
 
 foreach ($P1_languages as $value) {
                                                
 $i++;
 $string .= $value['language'];
                                                
 if ( $i < $total ) { $string .= ', '; }
                                                 
 } 
                                            
 echo $string;  
?>
 
but my problem now is . . .

if a user did not input any language,
still the out would be

Code: Select all

,
the comma... and not blank.

how would i solve this?
so that if a user doesn't have any language input the output would just blank.

thanks again.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: how to add "commas" and the word "and" before the last entry

Post by John Cartwright »

You have a $total variable, so check against that..

Code: Select all

if ($total > 0) {
   //do your stuff
}
melchor_06
Forum Newbie
Posts: 13
Joined: Wed Feb 11, 2009 3:58 am

Re: how to add "commas" and the word "and" before the last entry

Post by melchor_06 »

this code works perfectly fine if there are datas inside the database but when there's nothing inside, that's my problem.

Code: Select all

 
 <?php if ( $languages )  { ?>   
   <dl class="clearfix">       
        <dt>His spoken languages</dt>
       <dd>
             <?php 
                $string = '';                           
                $i = 0;
                $total = count($languages);
                                            
                foreach ($languages as $value) {
                                                        
                     $i++;
                     $string .= $value['language'];
                                                        
                     if ( $i < $total ) { $string .= ', '; } 
                                                    
                }
                    echo $string;
             ?>
      </dd>
    </dl>
 <?php } ?>
 
the ouput would still be

Code: Select all

 
His spoken language
 
i really need to eliminate this...

there are posted answers to this but still no luck . . .

i really need to solve this guys....

by the way sorry if i posted a new thread to this one...

thanks again guys...

i hope someone could h
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: how to add "commas" and the word "and" before the last entry

Post by John Cartwright »

Move all the relevant text inside the if (count($total)) {

:?
melchor_06
Forum Newbie
Posts: 13
Joined: Wed Feb 11, 2009 3:58 am

Re: how to add "commas" and the word "and" before the last entry

Post by melchor_06 »

i'm a bit new to php.
can you elaborate more the solution.
sorry for my stupidity.
thanks.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: how to add "commas" and the word "and" before the last entry

Post by John Cartwright »

We are here to faciliate your learning. With that said, let me illustrate the problem to help you come to your own solution.

Code: Select all

<?php
$name = false;
echo 'Hi there Mr. ';
if ($name) {
   echo $name;
}
echo '!';
 
//outputs Hi there Mr. !
 
?>
Obviously $name is always evaluated as false, and therefore it will never enter the if block. Now, in your situation, similarily, we need to check whether we have a $total (in my example $name) to see if it makes sense to output the preceding text. Considering it may not always be needed to enter the if block, we will move all relevant text within the if block.

Code: Select all

<?php
 
$name = false;
if ($name) {
   echo 'Hi there Mr. ';
   echo $name;
   echo '.';
}
?>
As you can see, we only output the text when the circumstance is appropriate.
melchor_06
Forum Newbie
Posts: 13
Joined: Wed Feb 11, 2009 3:58 am

Re: how to add "commas" and the word "and" before the last entry

Post by melchor_06 »

this code works perfectly fine.

Code: Select all

 
<?php if ( $languages )  { ?>  
    <dl class="clearfix">      
         <dt>His spoken languages</dt>
        <dd><?php $languages;  ?>
       </dd>
     </dl>
  <?php } ?>
 
if there's no data inside the variable. this code fits perfectly.

the output would just be totally blank.

but if the variable has multiple inputs inside this code definitely won't work same as the code i posted earlier.

i appreciate your help Mr. John Cartwright, really thank you.

but can't we stick to my code for the solution?

it would be a great help!

thanks!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: how to add "commas" and the word "and" before the last entry

Post by John Cartwright »

Ah sorry, I misunderstood the issue. However, in my defence the exact same logic applies.

When building html lists, I find it much easier to build an array of elements and implode then, rather than having to use logic to determine when to put a comma.

Code: Select all

<?php 
 
$spoken = array();
if ($languages)  { 
    foreach ($languages as $value) {
        if (!empty($value['language'])) {
            $spoken[] = $value['language'];
        }            
    }
    
    if (count($spoken)) {
?>
        <dl class="clearfix">      
           <dt>His spoken languages</dt>
           <dd>
              <?php echo implode(',', $spoken); ?>
           </dd>
        </dl>       
<?php 
    }
} 
 
 
?>
melchor_06
Forum Newbie
Posts: 13
Joined: Wed Feb 11, 2009 3:58 am

Re: how to add "commas" and the word "and" before the last entry

Post by melchor_06 »

wow, it works now!!!

thanks for the big help Mr. John Cartwright.

you're the man. :D
Post Reply