Website Development Prices

Website Development Prices

Sunday, January 17, 2016

Prekid izvrsenja petlje (Terminate execution of loop)

Ako zelite ranije da prekinete petlju ili iskaz switch, mozete koristiti iskaz break. Iskaz break prekida izvrsenje for, foreach, while, do...while i switch iskaza. 

Vec ste videli jedan primere u Upotreba iskaza switch.

Primer: prekidamo kod koji bi se izvrsio u okviru iskaza case, koji je deo iskaza switch.

<?php

$cenamotora = 2500;

switch ($cenamotora):
case '2500':
echo "Cena ovog motora je jeftina.";
break;
.
.
.


?>


Primer 2: pomocu iskaza break mozete da prekinete i izvrsenje petlje.

<?php

for ($brojac_petlje=0; $brojac_petlje < 5; $brojac_petlje++) {
echo "Ja cu ovo uraditi 5 puta, ako me ne prekinete.<br>";
if ($brojac_petlje == 3) {
echo "Hmm, ipak cu da stanem.<br>";
break;
}

}

?>


Rezultat:

Ja cu ovo uraditi 5 puta, ako me ne prekinete.
Ja cu ovo uraditi 5 puta, ako me ne prekinete.
Ja cu ovo uraditi 5 puta, ako me ne prekinete.
Ja cu ovo uraditi 5 puta, ako me ne prekinete.
Hmm, ipak cu da stanem.


If you want to stop earlier a loop or switch statement, you can use the break statement. The statement break terminates execution of for, foreach, while, do ... while, and switch statements.

You have already seen two examples in Using statement switch.

Example: we will stop code that would be executed within the statement case, which is part of statement switch.

<?php

$priceofbike = 2500;

switch ($priceofbike):
case '2500':
echo "The price of this motobike is cheap.";
break;
.
.

.

?>

Example 2: using the statement break you can stop the execution of the loop.

<?php

for ($loop_counter=0; $loop_counter < 5; $loop_counter++) {
echo "I will do this 5 times, if you do not stop me.<br>";
if ($loop_counter == 3) {
echo "Hmm, I will stop.<br>";
break;
}

}

?>

Result:

I will do this 5 times, if you do not stop me.
I will do this 5 times, if you do not stop me.
I will do this 5 times, if you do not stop me.
I will do this 5 times, if you do not stop me.
Hmm, I will stop.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.