Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJoshua Russo
10,037 PointsPHP Syntax
I've tried for while to learn php. I just simply don't understand how you are ending the php tags in conditionals with <?php _____ { ?> <?php ?> How does all that work? When do you use "{ ?>" I want to be a php developer for my job, but I just don't get these breaks in closing and conditional tags.
5 Answers
Jinxi Wu
101 PointsThis might be helpful:
http://www.php.net/manual/en/language.basic-syntax.phptags.php
Joshua Russo
10,037 PointsThank you for that reply, but I'm wondering more about the {?> part. Why the curly brackets and why does the code continue like <?php } ?> or something like that.
thomascawthorn
22,986 PointsI see what you're saying -
when the php conditionalsi are split between different php tags on different lines?
<?php if (true) { ?>
Do This
<?php } else { ?>
Do this
<?php } ?>
Joshua Russo
10,037 PointsYes, that part. But you can have echo statements that don't say "if, true or else".
<?php foreach($products as $product) { //here
echo "<li>";
echo '<a href="#">';
echo '<img src="' . $product["img"] . '" alt="' . $product["name"] . '">';
echo "<p>View Details</p>";
echo "</a>";
echo "</li>";
} //here
?>
Such as in some coding for the track, "Build a simple PHP application".
thomascawthorn
22,986 PointsI'm with you!
Both are absolutely valid methods, but there is always a 'better way'. Considering DRY (don't repeat yourself) Is it more or less work to write echo for every line ;)
I've not been going a long time with PHP but they way I figure it - whatever works best for you!
If your html outweighs your php, then it's probably simpler to put a closing php tag when you open the initial statement, write the html with intermittent php. Then close the loop in php tags at the end.
<?php foreach ($products as $product) { ?>
Loads of html
<?php echo "php splash" ?>
loads of html
<?php } ?>
If you have a lot of php going on, you may be better off echoing out statements of html - i.e. if this is simpler than writing lots of opening and closing php tags.
<?php foreach ($products as $product) {
//php;
//more php;
//wow there's a lot of php;
echo "a piece of html";
}
Both ways would achieve the same result :)
The php will only stop running at an 'end' ('die' etc...) statement . not when it hits the end of a php closing tag, which is why you can split the curly braces between different php tags. Handy eh!