Google News
logo
Hack - Interview Questions
What are the different types of loops in Hack?
Hack supports several types of loops that allow you to iterate over data structures or execute a block of code repeatedly. Here are the different types of loops available in Hack:

1. For Loop : The `for` loop is used to iterate a specific number of times. It consists of an initialization statement, a condition, an increment/decrement statement, and the loop body.
for ($i = 0; $i < 5; $i++) {
  // Loop body
  // Code statements
}​

In the above example, the loop will execute as long as `$i` is less than 5. The `$i` variable is incremented by 1 in each iteration.

2. Foreach Loop : The `foreach` loop is used to iterate over arrays and other iterable data structures, such as collections or maps. It automatically traverses each element in the data structure without the need for an explicit counter.
foreach ($array as $element) {
  // Loop body
  // Code statements
}​

In the above example, `$array` is an array, and `$element` represents the current element being iterated. The loop body will execute for each element in the array.
3.  While Loop : The `while` loop repeatedly executes a block of code as long as a given condition is true. It evaluates the condition before each iteration.
while (condition) {
  // Loop body
  // Code statements
}​

In the `while` loop, the condition is checked, and if it evaluates to true, the loop body is executed. The loop continues until the condition becomes false.

4.  Do-While Loop : The `do-while` loop is similar to the `while` loop but with a crucial difference: it executes the loop body at least once before checking the condition.
do {
  // Loop body
  // Code statements
} while (condition);​

In the `do-while` loop, the loop body is executed first, and then the condition is evaluated. If the condition is true, the loop continues, otherwise, it terminates.

These are the main types of loops available in Hack. You can choose the loop structure that best fits your requirements based on the nature of the iteration and the condition you need to evaluate.
Advertisement