Website Development Prices

Search Blog

Sunday, November 22, 2015

Ternarni operator (Ternary operator)

Terinarni operator(?:) se ponasa isto kao i iskaz if.

$cenamotora = uslov : izraz1 : izraz2;

Ako je uslov tacan, onda se promenljivoj $cenamotora dodeljuje vrednost izraz1, u suprotnom se dodeljuje vrednost izraz2

<?php

$cenamotora = 2600;

if ($cenamotora > 2500 && $cenamotora < 3000) {
echo "Cena je pristupacna.";
}

else {
echo "Cena nije pristupacna.";
}

?>

Ovaj fajl sacuvajte kao ternarni-operator.php.


Ako koristite ternarni operator ovaj kod moze se skratiti na dva reda.

<?php

$cenamotora = 2600;

echo $cenamotora > 2500 && $cenamotora < 3000 ? 
"Cena je pristupacna." : "Cena nije pristupacna.";


?>

Ternary operator (? :) behaves the same as the if statement.

$priceofbike = condition : expression1 : expression2;

If the condition is true, then the variable $priceofbike assigns the value of 
expression1, otherwise it assigns the value of expression2.

$priceofbike = 2600;

if ($priceofbike > 2500 && $priceofbike < 3000) {
echo "Price is affordable.";
}

else {
echo "Price is not affordable.";
}

?>

Save this file as ternary-operator.php.

If you use the ternary operator this code can be shortened to two rows.

<?php

$priceofbike = 2600;

echo $priceofbike > 2500 && $priceofbike < 3000 ? 
"Price is affordable." : "Price is not affordable.";


?>

No comments:

Post a Comment

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