-3

Here is a situation I need to display values from array through foreach loop inside variable and than echo that variable inside HTML table. Thanks in Advance. . I have checked all related links in stackoverflow some links are given below.

PHP simple foreach loop with HTML [closed]

My question is about store looping array inside a variable.. And their is no similarity in another and my question

I want my output to be this way below Output link

I'm getting this error image given below Error image link here

php filename: foreachloop.php

    <?php
$arr = array("Apple","orange","strawberry");
$abc = '<table border="2">
            <tr>
                <th>Names</th>
            </tr>
            foreach($arr as $key){
            <tr>
                <td>'.$key.'</td>
            </tr>
        }
        </table>';

echo $abc;
?>
2
  • 1
    it is clear in your error message. Commented Apr 2, 2017 at 12:41
  • i'm unable to figure it out because foreach loop is inside variable and i want the same way Commented Apr 2, 2017 at 12:43

2 Answers 2

4

Because, you are messing php and html code

$arr = array("Apple","orange","strawberry");
$abc = '<table border="2">
            <tr>
                <th>Names</th>
            </tr>';
            foreach($arr as $key){
            $abc.='<tr>
                <td>'.$key.'</td>
            </tr>';
        }
        $abc.='</table>';

echo $abc;

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

You have miss placed the foreach. It is a code block and you have placed it inside the quotes, which will be treated as text. Check the below code.

<?php
    $arr = array("Apple","orange","strawberry");
    $abc = '<table border="2"><tr><th>Names</th></tr>';
    foreach($arr as $key){
        $abc .= '<tr><td>'.$key.'</td></tr>';
    }
    $abc .= '</table>';
    echo $abc;
?>

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.