0

I have code like such:

function myFunction(){
    $types = getTypes();

    for ($i = 0; $i < count($types); $i++) {
        $projects = getProjects($types[i]);
        echo "<div class='block'>";
        for ($a = 0; $a < count($projects); $a++) {  
            echo "
                <p>
                    <a href='{$projects[$a]["link"]}'>{$projects[$a]["title"]}</a>
                    {$projects[$a]["description"]}

                </p>
            ";
        }
        echo " </div> ";
    }
}

And then in an html file:

<section>
    <?php myFunction(); ?>
</section>

Unless I set custom settings, beautifiers mess with the string formatting, I can't use double quotes, and all my html gets coloured the same way in any IDE. This had let me to believe this is not the way html is intended to be put in php scripts. What is the proper way of doing this?

4
  • 1
    Use a template or best is to switch to a framework Commented Dec 8, 2018 at 18:42
  • This depends upon which IDE you're using IDE plugin for PHP can help you to recognize your language. And this is the correct way, alternatively you can return something from function and then parse it inside html but this will be the same thing apparently. Commented Dec 8, 2018 at 18:42
  • @vivek_23 can you elaborate on the template comment? How would I go about doing this? Commented Dec 8, 2018 at 18:44
  • 1
    @Jersh You can use the Smarty template. It's a better way to represent html with using PHP variables and interpolation {}. Commented Dec 8, 2018 at 18:51

2 Answers 2

2

There are many ways to write the code. For example, you can make it like:

$projects = getProjects($types[i]);
?>
<div class="block">
<?php for ($a = 0; $a < count($projects); $a++) : ?>  
    <p>
        <a href="<?php echo $projects[$a]['link'];?>"><?php echo $projects[$a]['title']; ?></a>
        <?php echo $projects[$a]['description']; ?>
    </p>
<?php endfor; ?>
</div>
<?php
Sign up to request clarification or add additional context in comments.

3 Comments

Right, but would this work nested in a for loop or function?
Yes, it would work. Althought there is a typo: endofr should be endfor
@Jersh yes it would work nested. Either you can insert the whole code in the html template.
1

I don't know if this is the "proper way", or even a good way, but it works for me. I use sprintf to create html. It compartmentalizes the quoting (at least in my brain). Something like this:

$f1 = ' <a href="%s">%s</a>%s';
echo "<p>",
    sprintf($f1,"link","title","description"),
    "</p>";

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.