Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Increment and Decrement | Loops
Introduction to PHP
course content

Зміст курсу

Introduction to PHP

Introduction to PHP

1. First Acquaintance
2. Variables and Data Types
3. Conditional Statements
4. Arrays
5. Loops

bookIncrement and Decrement

Increments (++) and decrements (--) are used to conveniently adjust variable values by 1. They are commonly employed in loops to modify loop counters for iterating through arrays or objects. They are also useful for incrementing or decrementing variable values in various algorithms that require sequential data processing or calculations.

Pre-increment and post-increment differ in when the variable's value is incremented relative to its use in an expression:

Pre-increment (++i)
The variable is incremented by 1 before being used in the expression. For example, if i = 5, the expression ++i will first increment i to 6, then return 6.

Post-increment (i++)
The variable is incremented by 1 after being used in the expression. For example, if i = 5, the expression i++ will first return 5, then increment i to 6.

Using Pre-Increment


php

main

copy
1234567891011
<?php // Initialize the variable $counter = 0; // Prefix increment echo ++$counter; // Output: 1 echo ++$counter; // Output: 2 echo ++$counter; // Output: 3 // The variable `$counter` now has the value 3 ?>

In this example, the variable $counter is incremented by 1 before its value is used for output. Each subsequent call of ++$counter increases $counter by 1, sequentially outputting 1, 2, and 3.

Using Post-Increment


php

main

copy
1234567891011
<?php // Initialize the variable $counter = 0; // Postfix increment echo $counter++; // Output: 0 echo $counter++; // Output: 1 echo $counter++; // Output: 2 // The variable `$counter` now has the value 3 ?>

In this example, the variable $counter is incremented by 1 after its value is used for output. Each subsequent call of $counter++ uses the current value of $counter for output and then increases $counter by 1, sequentially outputting 0, 1, and 2.

Pre-Increment in a Loop


php

main

copy
123456789
<?php // Initialize the counter variable $counter = 0; // `for` loop with prefix increment for ($i = 0; $i < 5; ++$i) { echo $i . " "; // Output the value of the counter } ?>

In this example, $i starts at 0. After each iteration of the for loop, it is incremented by 1 using the prefix increment ++$i. As a result, the loop outputs numbers from 0 to 4.

What will be the value of the variable $result after the following code is executed?

What will be the value of the variable $result after the following code is executed?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 5. Розділ 5
We're sorry to hear that something went wrong. What happened?
some-alt