use the PHP implode

Asked

Viewed 256 times

2

I need to put the result this way: valora,valorB,valorC. I am using the code below:

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

$array = array($valor);

echo implode(",",$array);

Only using this way, I’m not getting. The values of the variables $value, comes through a checkbox in HTML.

  • Post the form as well, so we can analyze.

  • Hello, there are several ways to create arrays and the one you just used there is obviously not the best or correct at all, someone answered your question, but I don’t really understand why you want something like this.

3 answers

8


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

You need to do it like this:

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

echo implode(",",$valor);

5

$varArray   = array();

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

echo implode(",", $varArray);

1

Based only on the code you posted:

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

It could be altered to give you the desired result:

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

Now, if you really need an array, you’ll have to start an array first, and fill it with the values (basically what @Rodrigorigotti answered!):

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

And then you can use the implode:

echo implode(",",$valor);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.