-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;
?>
Ravi
  • 30,829
  • 42
  • 119
  • 173
Pavan Baddi
  • 479
  • 1
  • 11
  • 22

2 Answers2

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

Ravi
  • 30,829
  • 42
  • 119
  • 173
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;
?>
elansha
  • 3
  • 1
  • 5