1

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
2
  • Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING Commented Jul 26, 2011 at 17:36
  • You mean concatenate not encapsulate : ) Commented Jul 26, 2011 at 17:44

4 Answers 4

5
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>';
}
Sign up to request clarification or add additional context in comments.

Comments

2
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.

Comments

0

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.
   }
}

Comments

0

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.

1 Comment

This should be a comment - but to clarify, commas are only faster if there is a variable in the mix. echo 'aaaa'.'aaaa'.'aaa'; is more than twice as fast as echo 'aaaa','aaaa','aaa';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.