开发者

How to encapsulate this variable into the string?

I want to encapsulate this variable into the string, but I always get an error:

for($i = 0; $i < $_POST['rows']; $i++) {
   echo "<tr>"
   for($j = 0; $j < $_POST['columns'] $j++) {
      echo "<td>$_POST['row{$i}column{$j}']</td>"; // << I 开发者_运维技巧get an error. Please help me encapsulate this.. I'm so confused.
   }
}

The error is:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING


for($i = 0; $i < $_POST['rows']; $i++) {
   echo '<tr>';
   for($j = 0; $j < $_POST['columns'] $j++) {
      echo '<td>' . $_POST['row' . $i . 'column' . $j] . '</td>';
   }
   echo '</tr>';
}


for($i = 0; $i < $_POST['rows']; $i++) {
   echo "<tr>"
   for($j = 0; $j < $_POST['columns'] $j++) {
      echo '<td>'.$_POST['row'.$i.'column'.$j].'</td>';
   }
}

Just concatenate the String with the . operator.


First of all you are missing ";" after echo "<tr>" second you are missing ";" after $_POST['columns']

and this is your solution

for($i = 0; $i < $_POST['rows']; $i++) {
   echo "<tr>";
   for($j = 0; $j < $_POST['columns']; $j++) {
      echo "<td>{$_POST['row{$i}column{$j}']}</td>"; // << I get an error. Please help me encapsulate this.. I'm so confused.
   }
}


The question has been answered, but I would like to point out a little known fact about echo.

echo '<td>' . $_POST['row'.$i.'column'.$j] . '</td>';

In this code, two concatenations are taking place,

'row' . $i . 'column' . $j, and

'< td >' . $_POST[...] . '< / td >'

A concatenation requires a temporary variable to be created on the stack, value transferred into the variable, and then the temp var passed into, in this case, either the array ref or the echo construct.

To save time and memory, try this instead:

echo '<td>', $_POST['row'.$i.'column'.$j], '</td>';

echo can take multiple arguments separated by columns. This saves both the time and memory consumed by a concatenation. Not much saved in the short run, but over time the improvement will add up. And it reduces confusion down the road over what is being concatenated, and what is being passed to output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜