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

Increment 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

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

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

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?

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

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

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