Question

How to implode many available to one available using loop for ?

i have many available like

$var_1 = one;
$var_2 = two;
$var_3 = three;
$var_4 = four;
$var_5 = five;
$var_6 = six;
$var_7 = seven;
$var_8 = eight;
$var_9 = nine;
$var_10 = ten;
$var_11 = eleven;

and then i want to implode to one available

$all_data = one,two,three,four,five,six,seven,eight,nine,ten,eleven,

but i want to using loop for like this

for ( $i=1;$i<12;$i++ )
{
$all_data = ${var_$i}.",";
}

how can i do ? thank you for every comment ^^

Was it helpful?

Solution

$all_data = implode(',', array($var_1, $var_2, ..., $var_11));

Any time you find yourself creating a bunch of variables with numeric names like this, say to yourself: "I really should be using an array". There's almost never a good reason for this type of programming.

For the for loop you're trying to write, see the PHP documentation on Variable Variables.

$all_data = '';
for ($i = 1; $i < 12; $i++) {
    $all_data .= ${'var_'.$i} . ',';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top