Remove last comma from an array

8

In this code below I have an array that returns me a comma at the end  exe: '98602', '98603', '98604',

How can I remove this comma?

 if (isset($_POST['checkbox'])) {
 foreach ($_POST['checkbox'] as $key => $value) {
    $id = mysql_real_escape_string($value);

    $regra = "'{$id}',";
    echo $regra;       
 }}
    
asked by anonymous 06.03.2015 / 16:09

5 answers

11

After the foreach use substr to remove the last character:

If the last parameter (lenght) is negative it will remove the characters at the end of the string. Do not forget to start $regra otherwise your value will always be reset every time you go.

 if (isset($_POST['checkbox'])) {
    $regra = '';
    foreach ($_POST['checkbox'] as $key => $value) {
      $id = mysql_real_escape_string($value);

      $regra .= "'{$id}',";

    }
    $regra = substr($regra, 0, -1);
    echo $regra;
 }

Another way to format this string at once is to combine the first and last single quotation marks between implode calls:

$arr = array('98602','98603','98604'); // equivalente o $_POST
$novo = "'". implode("','", $arr) ."'";
echo 'implode '. $novo;

Output:

'98602','98603','98604'
    
06.03.2015 / 16:12
8

There are several ways, you can even make an algorithm that it is not inserted. I think the easiest would be rtrim() :

if (isset($_POST['checkbox'])) {
    foreach ($_POST['checkbox'] as $key => $value) {
        $id = mysql_real_escape_string($value);
        $regra = "'{$id}',";
        echo $regra;       
    }
    rtrim($regra, ',');
}
    
06.03.2015 / 16:12
5

Based on what @bigown mentioned, one way is not to enter the comma, rather than to remove it. Note that the code is longer than rtrim :

$regra = '';
$separador = '';
if ( isset( $_POST['checkbox'] ) ) {
   foreach ( $_POST['checkbox'] as $value ) {
      $regra .= $separador."'".mysql_real_escape_string( $value )."'";
      $separador = ',';
   }
}
echo $regra;       

I made a small optimization by taking out echo of the main logic and removing $key => and $id that are not needed in this case.

    
06.03.2015 / 16:45
5

You can map this array and then join the array elements with commas in the middle:

$func = function($value) {
     $id = mysql_real_escape_string($value);
     return "'{$id}'";
};

$ids = array_map($func, $_POST['checkbox']);
echo implode(",", $ids);

You have other correct answers, this is another approach that I prefer. if (isset($_POST['checkbox'])) is still required, this part you can keep.

    
06.03.2015 / 16:57
-2

Another way of solving it would also be

if (isset($_POST['checkbox'])) {
  $regra = "";
  foreach ($_POST['checkbox'] as $key => $value) {
    $id = mysql_real_escape_string($value);

    $regra .= ($regra != "" ? "," : "") . "'{$id}'";
  }
 }
    
14.03.2015 / 14:06