0

I want to read 5 attributes of the database. The 5 attributes have the names post_image_1, post_image_2, post_image_3, post_image_4 and post_image_5. Now I want to show the 5 images on my page, with a for loop.

Here is the loop:

for($i = 1; $i <= 5; $i++){
    echo "<img src='image/$row[post_image_$i].png' height='250px' width='250px'>";
}

Now I get an error:

Parse error: syntax error, unexpected '$i' (T_VARIABLE), expecting ']' in

I hope that's enough info to help me. :P

1
  • 1
    You are trying to mix a constant and variable name together in your array index key as far as PHP is concerned. Commented Feb 6, 2015 at 21:18

2 Answers 2

4

Since you're using arrays, do this:

for($i = 1; $i <= 5; $i++){
    echo '<img src="image/'.$row['post_image_'.$i].'png" height="250px" width="250px">';
}
Sign up to request clarification or add additional context in comments.

2 Comments

beat me by seconds... :)
A for effort ;) - in fact, if OP catches this, you can take the answer points - the upvotes already got me back over 2,000 -
2

Try this, using string concatenation, it gets at the right field in the array. I'm assuming $row is declared already and contains the keys 'post_image_1', 'post_image_2'...

for($i = 1; $i <= 5; $i++){
    echo "<img src='image/" . $row['post_image_' . $i] . ".png' height='250px' width='250px'>";
}

Comments

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.