What is this Colon inside foreach for php?

Ok, I'm officially embarrassed. I read about this MVC intro in php, and I see this code, and I added some elements to the array above to see if it really works.

<?php $members = array('apple', 'oranges', 'banana'); ?> <html> <h1>Members of community.com:</h1> <ul> <?php foreach ($members as $i => $member) : ?> <li>Member #<?php echo $i + 1; ?>: <?php echo $member; ?></li> <?php endforeach; ?> </ul> </html> 

I noticed there a: in the foreach statement line. Where does this come from? More importantly, what is it? This: the symbol means "okay, we will continue this statement in the next line"?

But also, this is a cool trick that I recognized. Fewer html tags inside my php echo, I think.

let me know what you think, thanks!

+8
arrays php foreach
source share
2 answers

This is the "Alternative Syntax for Control Structures" ... see http://ru2.php.net/manual/en/control-structures.alternative-syntax.php and http://www.php.net/manual/en /control-structures.foreach.php#82511 .

It is mainly used in a code of view that designers can look at because it is thought to be easier to understand for non-programmers. I highly recommend not using it, as it really does not offer anything regarding the commented set of curly braces, and many IDEs do not play well with it. If your code may ever be needed for others to view, it is best to use the code without using alternative syntax.

 foreach ($setOfItems as $item): //do something endforeach; 

better represented as ...

 foreach ($setOfItems as $item) { //do something } // end ($setOfItems as $item) foreach 

Once you start embedding a few sets of structures that end with an endstructure; instead of brackets, then the commented brackets give a more detailed description of which block ends. You can, of course, comment on the final structure; syntax, but you still have a problem that many IDEs will not be able to match them for you.

+7
source share

This means that foreach will continue until it reaches endforeach . This is the alternative syntax {} .

See http://www.php.net/manual/en/control-structures.foreach.php#82511

+7
source share

All Articles