{
    "slug": "php_casting",
    "term": "Type Casting in PHP",
    "category": "php",
    "difficulty": "beginner",
    "short": "Explicitly converting a value to another type using (int), (string), (array), (object) casts or intval(), strval() functions.",
    "long": "PHP supports explicit casting with (int), (bool), (float), (string), (array), (object), and (unset) (removed in PHP 8.0). Casting rules have edge cases: (int)'10abc' === 10, (bool)'' === false, (bool)'0' === false, (array)null === [], (array)'hello' === ['hello']. For integers, intval() allows a base parameter. For security-sensitive conversions, prefer intval() or settype() over casts — the intent is clearer and linting tools flag misuse more reliably. In PHP 8.0+ with strict_types, casting becomes less necessary as type errors are thrown for mismatched arguments.",
    "aliases": [
        "PHP type casting",
        "(int)",
        "(string)",
        "settype"
    ],
    "tags": [
        "php",
        "type-system",
        "type-coercion"
    ],
    "misconception": "(int)$val and intval($val) are always identical. They produce the same result for most inputs but differ on objects — intval() on an object returns 1, while (int) on an object produces a notice in PHP 8. For arrays, both return 0 or 1 based on emptiness.",
    "why_it_matters": "PHP's casting operators (int), (float), (bool), (array) perform type coercion — understanding their edge cases prevents silent data corruption, especially with null, empty strings, and '0'.",
    "common_mistakes": [
        "(bool)'0' is false — the string '0' is the only non-empty string PHP treats as falsy.",
        "(int)'123abc' returns 123 silently — use filter_var() with FILTER_VALIDATE_INT for actual validation.",
        "(array)null returns [] but (array)$object returns an array of properties — different behaviours for different types.",
        "Casting floats to int truncates rather than rounds — (int)4.9 is 4, not 5."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "type_juggling",
        "type_coercion",
        "strict_types",
        "intval"
    ],
    "prerequisites": [
        "type_juggling",
        "strict_types",
        "type_declarations"
    ],
    "refs": [
        "https://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting"
    ],
    "bad_code": "// Silent data corruption:\n$val = (int)'12.5kg'; // Returns 12 — no error, 'kg' silently dropped\n$flag = (bool)'0';    // Returns false — '0' is the only falsy non-empty string\n$arr = (array)null;   // Returns [] — not an error\n\n// '0' trap:\nif ((bool)$_GET['active']) {} // ?active=0 evaluates to false unexpectedly",
    "good_code": "// Explicit casts — prefer over implicit coercion\n\\$id    = (int)    \\$_GET['id'];    // '42abc' → 42, 'abc' → 0\n\\$price = (float)  \\$_POST['price'];\n\\$flag  = (bool)   \\$value;\n\\$str   = (string) \\$object;        // calls __toString()\n\\$arr   = (array)  \\$object;        // public properties as array\n\n// intval() with base\n\\$oct = intval('0777', 8);  // 511\n\\$hex = intval('FF', 16);   // 255\n\n// settype() — mutates the variable\nsettype(\\$value, 'integer');\n\n// Falsy values in PHP — know them\n// false, 0, 0.0, '0', '', '0.0', [], null → all falsy\n// '00', '0.0', ' ' → TRUTHY (non-empty, non-'0' strings)\nvar_dump((bool)'00'); // true — common surprise",
    "quick_fix": "Use (int), (float), (bool), (string) for explicit conversion in contexts you control; use intval/floatval/strval for user input; never rely on implicit type coercion in strict_types code",
    "severity": "medium",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/php_casting",
        "html_url": "https://codeclaritylab.com/glossary/php_casting",
        "json_url": "https://codeclaritylab.com/glossary/php_casting.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Type Casting in PHP](https://codeclaritylab.com/glossary/php_casting) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/php_casting"
            }
        }
    }
}