如何在switch case中回显PHP代码

如何在switch case中回显PHP代码

问题描述:

So I have this code that should display price in one case and "Paid" text in other:

<?php
switch($order['status'])
{
    case 0:
        echo  
        '<div class="paiment">
                <p>Some text</p>
                <ul>
                    <li>More text</li>
                    <li>More text</li>
                    <li>Important text:
                        <?php foreach($something as $item): ?>
                            <?php
                            $unitPrice = HelperItem::displayItemPrice($item["price"], true, $configuration);
                            ?>            
                            <?php echo $unitPrice; ?>
                        <?php endforeach; ?>
                    </li>
                </ul>
        </div>'
        ;
        break;
    case 1:
        echo 'Paid';
        break;
}
?>

I need some way to make this "foreach" work inside "echo". I've tried with removing "" and doing something like this: echo 'xxxx' . code . 'xxxx' but all I got was errors. Is it even possible to make this work?

You're very close, just need to break things up around the foreach:

<?php
switch($order['status'])
{
    case 0:
        echo  
        '<div class="paiment">
                <p>Some text</p>
                <ul>
                    <li>More text</li>
                    <li>More text</li>
                    <li>Important text:';
                        foreach($something as $item)
                            echo HelperItem::displayItemPrice($item["price"], true, $configuration);
                    echo '</li>
                </ul>
        </div>'
        ;
        break;
    case 1:
        echo 'Paid';
        break;
}
?>

You cannot echo a foreach. Maybe try something like:

echo "xxxx";
foreach(){ }
echo "xxxx";