use the PHP implode

2

I need to put the result in this way: valueA, valueB, valueC. I'm using the code below:

$valor = "valorA";
$valor .= "valorB";
$valor .= "valorC";

$array = array($valor);

echo implode(",",$array);

Only using it that way, I can not. The values of the $ value variables come from an HTML checkbox.

    
asked by anonymous 31.08.2015 / 19:41

3 answers

8

The final content of $valor is a string containing valorAvalorBvalorC , not an array.

You need to do this:

$valor   = array();
$valor[] = "valorA";
$valor[] = "valorB";
$valor[] = "valorC";

echo implode(",",$valor);
    
31.08.2015 / 19:46
5
$varArray   = array();

foreach($_POST['NAME_CHECKBOX'] as $item){
   $varArray[] = $item;
}

echo implode(",", $varArray);
    
31.08.2015 / 19:52
1

Based only on the code you posted:

$valor = "valorA";
$valor .= "valorB";
$valor .= "valorC";

It could be changed to give you the desired result:

$valor = "valorA";
$valor .= ",valorB";
$valor .= ",valorC";

Now, if you really need an array, you'll have to initialize an array first, and fill in the values (basically what @RodrigoRigotti replied!):

$valor = array();
$valor[] = "valorA";
$valor[] = "valorB";
$valor[] = "valorC";

And then you can use the implode:

echo implode(",",$valor);
    
31.08.2015 / 19:56