What are the different data types in PHP? PHP में अलग-अलग डेटा टाइप्स कौन से हैं?
Short Answer
The switch statement is a control structure used as a cleaner alternative to a long series of if...elseif...else blocks. It compares a single variable against multiple possible values (cases) and executes the corresponding block of code.
Detailed Explanation & Code Example
Each condition in a switch block is called a case. When a case matches the variable, PHP executes the code inside that case until it hits a break statement.
$role = "editor";
switch ($role) {
case "admin":
echo "You have full access.";
break;
case "editor":
echo "You can publish posts.";
break;
case "subscriber":
echo "You can read posts.";
break;
default:
// The default block runs if no cases matched
echo "Please log in.";
}
// Output: You can publish posts.
Common Mistakes: The "Fall-Through" Bug
If you forget to include the break; statement at the end of a case, PHP will execute the matched case and all subsequent cases until it hits a break or the switch ends. This is called "falling through."
// BAD CODE: Missing break statements
$number = 1;
switch ($number) {
case 1:
echo "One ";
case 2:
echo "Two ";
}
// Output: One Two
PHP loosely typed है — वेरिएबल्स को टाइप डिक्लेयर करने की ज़रूरत नहीं। इसमें 8 प्रिमिटिव टाइप्स होते हैं:
| टाइप | उदाहरण | नोट्स |
|---|---|---|
| String | "Hello" | कैरेक्टर्स की सीक्वेंस |
| Integer | 42 | पूर्ण संख्याएं |
| Float | 3.14 | दशमलव संख्याएं |
| Boolean | true / false | लॉजिकल वैल्यू |
| Array | [1,2,3] | वैल्यूज़ का ऑर्डर्ड मैप |
| Object | new ClassName() | क्लास का इंस्टेंस |
| NULL | null | कोई वैल्यू नहीं |
| Resource | File/DB handle | बाहरी रिसोर्स का रेफरेंस |
टाइप चेक करने के लिए gettype($var) और डिबगिंग में var_dump($var) इस्तेमाल करें।
Was this answer clear?