How can I easily remove the last comma from an arr

2020-02-07 02:05发布

Let's say I have this:

$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");

foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}

echoes "john-doe,foe-bar,oh-yeah,"

How do I get rid of the last comma?

10条回答
老娘就宠你
2楼-- · 2020-02-07 02:38

I dislike all previous recipes.

Php is not C and has higher-level ways to deal with this particular problem.

I will begin from the point where you have an array like this:

$array = array('john-doe', 'foe-bar', 'oh-yeah');

You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.

Now you need to generate a CSV string from this array, it can be done like this:

echo implode(',', $array);
查看更多
神经病院院长
3楼-- · 2020-02-07 02:39

I have removed comma from last value of aray by using last key of array. Hope this will give you idea.

   $last_key =  end(array_keys($myArray));
                           foreach ($myArray as $key => $value ) {
                              $product_cateogry_details="SELECT * FROM `product_cateogry` WHERE `admin_id`='$admin_id' AND `id` = '$value'";
                                  $product_cateogry_details_query=mysqli_query($con,$product_cateogry_details);
                                  $detail=mysqli_fetch_array($product_cateogry_details_query);

                                  if ($last_key == $key) {
                                    echo $detail['product_cateogry'];
                                  }else{
                                    echo $detail['product_cateogry']." , ";
                                  }

                          }
查看更多
爷的心禁止访问
4楼-- · 2020-02-07 02:40

I always use this method:

$result = '';
foreach($array as $i=>$k) {
    if(strlen($result) > 0) {
        $result .= ","
    }
    $result .= $i.'-'.$k;
}
echo $result;
查看更多
ら.Afraid
5楼-- · 2020-02-07 02:42

One method is by using substr

$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");

$output = "";
foreach($array as $i=>$k)
{
    $output .= $i.'-'.$k.',';
}

$output = substr($output, 0, -1);

echo $output;

Another method would be using implode

$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");

$output = array();
foreach($array as $i=>$k)
{
    $output[] = $i.'-'.$k;
}

echo implode(',', $output);
查看更多
登录 后发表回答