Home > php > คุณรู้หรือไม่ว่า php มี endfor, endif, endforeach, endwhile

คุณรู้หรือไม่ว่า php มี endfor, endif, endforeach, endwhile

May 8, 2011 No Comments    

หลายคนพัฒนาเว็บด้วยภาษา php มักเจอปัญหาเวลาหน้าเว็บที่ต้องใช้ผสมระหว่าง php กับ html ทำให้เกิดโค้ดที่ไม่สวยงาม แต่ php ก็ได้คิดค้น alternative syntax control ขึ้นมันก็คือพวก endfor, endif, endforeach และ endwhile นั้นเอง

php

แล้วพวกนี้มันนี้ยังไงละ มันมีวิธีใช้ตามนี้ครับ


<html>
<body>
<ul>
<?php $a = 10;?>
<?php if($a == 10):?>
<li>1</li>
<li>2</li>
<li>3</li>
<?php elseif($a==5):?>
<li>4</li>
<li>5</li>
<li>6</li>
<?php endif;?>

<?php if($a == 10){?>
<li>1</li>
<li>2</li>
<li>3</li>
<?php }
elseif($a == 5) {?>
<li>4</li>
<li>5</li>
<li>6</li>
<?php }?>
</ul>
</body>
</html>

จากโค้ดที่เห็นจะเห็นว่าถ้าแบบทั่วไปธรรมที่ใช้กัน ถ้ามันมีโค้ดเยอะๆๆ จะทำให้เราตาลาย เพราะเนื่องจากเครื่อง {} นั้นเองแต่ถ้าใช้ในรูปแบบ endif; นั้นจะทำให้เราสบายตามากขึ้นมันทำให้รู้สึกเหมือนสคลิปทั่วไปคล้ายๆพวก vb เป็นต้น ซึ่งการใช้โค้ดในรูปแบบ endif นั้นเหมาะสำหรับในหน้าที่เป็นส่วนของ view ที่ต้องมีการผสมระหว่าง html กับ php นั้นเอง

ส่วนเรื่องรูปแบบการใช้งานนั้นจะสังเกตเห็นว่ามีเครื่องหมาย : หลัง if นะครับ และนั้นคือวิธีใช้งานครับให้ใช้เครื่องหมาย : หลังเงื่อนไขเปรียบเสมือนวงเว็บเปิด และมันจะทำจนจบก็ต้องเมื่อเจอ endif; ครับ ส่วนพวกคำสั่งอื่นเช่น endfor; , endforeach; , endwhile ก็ใช้งานในลักษณะเดียวกัน

Tags: , , , , ,

Comments : คุณรู้หรือไม่ว่า php มี endfor, endif, endforeach, endwhile

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>