Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære If Statement | Conditional Statements
Introduction to PHP

book
If Statement

An if statement is a construct that allows you to execute a code block if a specific condition is met.

The condition is an expression that evaluates to a bool value, which can be true or false. If the condition is true, the block of code is executed. If the condition is false, the block of code is skipped.

Syntax


php
if (condition) {
// code block
};

The syntax of the conditional operator is so simple: if keyword, condition in the parentheses ( ) and a code block in the curly brackets { }.

The open curly bracket { } opens the code block, and the close curly bracket symbol closes it. Let's consider a example:

php

main

copy
<?php
$num=5;
if ($num>0) { // 5 > 0 ?
echo "Number is positive"; // output if it's `true`
}
?>
123456
<?php $num=5; if ($num>0) { // 5 > 0 ? echo "Number is positive"; // output if it's `true` } ?>

The condition was confirmed and the block of code worked. Let's consider a different example:

php

main

copy
<?php
$num = 10;
if ($num < 0) { // 10 < 0 ?
echo "Number is negative"; // output if it's `true`
}
?>
123456
<?php $num = 10; if ($num < 0) { // 10 < 0 ? echo "Number is negative"; // output if it's `true` } ?>

The condition was not confirmed, and the code block did not work.

Oppgave

Swipe to start coding

Complete the code to create a program that checks the price of a chocolate bar and prints the appropriate message. If the price of the chocolate bar is less than or equal to 3, the program should print "This chocolate bar has an average price". If the price of the chocolate bar is greater than 3, the program should print "This chocolate bar is expensive".

Løsning

<?php
$price_of_chocolate = 5;

if ($price_of_chocolate <= 3) {
echo "This chocolate bar has an average price.";
}

if ($price_of_chocolate > 3) {
echo "This chocolate bar is expensive.";
}
?>

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 1
<?php
$price_of_chocolate = 5;

___ {
echo "This chocolate bar has an average price.";
}

___ {
echo "This chocolate bar is expensive.";
}
?>

Spør AI

expand
ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

We use cookies to make your experience better!
some-alt