PHP Perulangan & Function Oleh: Ahmad Ramadhani, S.Kom
Perulangan (loop) Didalam php ada 4 syntax yang dapat digunakan untuk melakukan suatu perulangan, yaitu : While Do while For Foreach
while while (condition is true) { statement; } Contoh: <?php $a=1; while ($a<5) { echo "$a"; $a++; } ?>
Do while do { code to be executed; } while (condition is true); Contoh : <?php $a=1; do{ echo "$a"; $a++; }while ($a<5) ?>
for for (init counter; test counter; increment counter) { code to be executed; } Contoh : <?php for ($a=1;$a<=5;$a++) { echo "$a"; } ?>
foreach foreach ($array as $value) { code to be executed; } Contoh : <?php $a=array (10,20,30,40,50); foreach ($a as $value) { echo "$value<br>"; } ?>
function Bentuk umum : function functionName() { code to be executed; } Contoh: <?php function tulis() { echo "Hello world!"; } tulis(); ?>
Fungsi dengan argumen <?php function nama($a) { echo "hai, $a.<br>"; } nama("Jani"); nama("Hege"); nama("Stale"); nama("Kai Jim"); nama("Borge"); ?>
Fungsi dengan 2 argumen <?php function nama($a,$b) { echo "nama : $a, tahun : $b.<br>"; } nama("Jani","1990"); nama("Hege","1991"); nama("Stale","1992"); nama("Kai Jim","1993"); nama("Borge","1994"); ?>
Fungsi dengan default argumen <?php function nama($a="1990") { echo "tahun : $a.<br>"; } nama("1991"); nama("1992"); nama(); nama("1994"); nama("1995"); ?>
Fungsi dengan nilai kembali <?php function sum($x,$y) { $z=$x+$y; return $z; } echo "5 + 10 = " . sum(5,10) . "<br>"; echo "7 + 13 = " . sum(7,13) . "<br>"; echo "2 + 4 = " . sum(2,4); ?>