Robert John Concepcion
Robert John Concepcion

Reputation: 237

simplify the bulk of code

is there a way to make this code shorter the value of $val1 $val2 ....... is a result of a query

$val1 = 1;
$val2 = 2;
$val3 = 3;
$val4 = 4;
$val5 = 5;
$val6 = 8;
$val7 = 7;
$val8 = 8;
$val9 = 8;
$val10 = 9;
$val11 = 13;
$val12 = 12;

echo $val1.",".$val2.",".$val3.",".$val4.",".$val5.",".$val6.",".$val7.",".$val8.",".$val9.",".$val10.",".$val11.",".$val12; 

?>

is there i way to simplify this

echo $val1.",".$val2.",".$val3.",".$val4.",".$val5.",".$val6.",".$val7.",".$val8.",".$val9.",".$val10.",".$val11.",".$val12; 

Upvotes: 0

Views: 62

Answers (3)

hakre
hakre

Reputation: 197659

That is what arrays are for:

$vals = range(1, 12);
echo implode(',', $vals);

If you did not create an array first-hand you should convert the numbered variables into an array first:

$vals = array($var1, $var2, $var3, ... , $var12);
echo implode(',', $vals);

This would not change that much for the single echo call, but normally you can move it more up in the code so to reduce the complexity.

Upvotes: 1

CaptainCarl
CaptainCarl

Reputation: 3489

Put it in an array and loop through it might work.

$values = array(1, 2, 3, 4, 5, 6);
foreach ($values as $key => $value) {
   echo $value;
}

Upvotes: 0

Florent
Florent

Reputation: 12420

Use array() and implode():

$values = array(1, 2, 3, 4, 5, 8, 7, 8, 8, 9, 13, 12);
echo implode(',', $values);

Upvotes: 3

Related Questions