What is the difference between == and === in PHP? PHP में == और === में क्या अंतर है?
Short Answer
PHP supports several types of loops to execute a block of code repeatedly: for (when you know exactly how many times you want to loop), while (when you want to loop as long as a condition is true), and foreach (specifically designed to iterate over arrays and objects).
Detailed Explanation & Examples
1. The for Loop
Used when the number of iterations is known in advance.
for ($i = 1; $i <= 3; $i++) {
echo "Iteration: $i\n";
}
// Output: Iteration 1, Iteration 2, Iteration 3
2. The while Loop
Executes a block of code as long as the specified condition is true. The condition is evaluated before the loop runs.
$count = 1;
while ($count <= 3) {
echo "Count: $count\n";
$count++;
}
3. The foreach Loop
The easiest way to iterate over arrays without needing to track an index variable.
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "Fruit: $fruit\n";
}
Common Mistakes
Forgetting to increment the counter in a while loop (e.g., omitting $count++) will result in an infinite loop, crashing the script or exhausting server memory.
== ढीली तुलना है (सिर्फ वैल्यू compare करता है, type juggling allow करता है)। === सख्त तुलना है (वैल्यू और टाइप दोनों compare करता है)।
| एक्सप्रेशन | == रिजल्ट | === रिजल्ट |
|---|---|---|
"5" == 5 | true | false |
0 == "abc" | false (PHP 8+) | false |
null == false | true | false |
1 === 1 | true | true |
इंटरव्यू टिप: असली कोड में हमेशा === इस्तेमाल करें ताकि type juggling बग्स से बचा जा सके।
Was this answer clear?