简体   繁体   中英

Implode array with comma separated string but no comma after last string

I have used implode to separate the array. What I want is that my ids should be shown in brackets separated by commas, but after the last string there will be no comma. How can I show them in brackets with no comma after the last string?

<html>
   <head>
   </head>

   <body>
      <?php
         mysql_connect("localhost", "usename", "password") or die(mysql_error()); 
         mysql_select_db("dbname") or die(mysql_error()); 

         $ids=array();
         $data = mysql_query("SELECT id FROM information"); 
         while($row = mysql_fetch_assoc($data))  
         {
            $ids[]=$row["id"]; 
         } 
         echo implode(", ", $ids);
      ?>
   </body>
</html>
$arr = [1,2,3,4,5,6,7,8,9,10,12,13]; // array(1,2,3,4,5,6,7,8,9,10,12,13); for versions below 5.4

$str = "(".implode("), (", $arr).")";

echo $str;

Results in

(1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (12), (13)

If that's your expected behavior, you just add the opening and closing bracket as delimiters, which will separate the strings by it, but will result in lack of opening and closing bracket at the beginning and at the end (as it adds the glue AFTER each element, except the last), so you add it manually with concatenation.

It will take 1 and 2 for example and will add after 1 (because 2 is the last, it will only add AFTER 1 ) the delimiter ), ( will result in 1), (2 , thus adding the concatenated ( and ) results in (1), (2)

Provided I followed your question correctly. You'd use something like this

( We're passing variables by reference in this example ):

foreach($ids as $i => &$id) {
    $id = "({$id})";
}

$string = implode(", ", $ids);

Which will end up returning something like this:

(56), (74), (88), (100), (91), (61), (43), (47), (77), (2), (78), (61), (44), (6), (74), (90), (14), (86), (80)

Here is an example ( Note: It just uses randomly generated id 's )


In response to your comment :

Even with strings, this function works. See this example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM