Beginner LevelPHP 8+
How do explicit type casting and scalar conversion work in PHP?
❓ Interview Prompt: Explain explicit type casting operators ((int), (string), (bool), (array), (object)) and scalar conversion rules.
PHP allows converting values explicitly between data types using cast operators:
Cast Operators:
•
'(int)', '(integer)': Casts to integer. Floating points are truncated towards zero. Numeric strings ('"42.5"') become '42'. Non-numeric strings ('"abc"') become '0'.
•
'(bool)', '(boolean)': Casts to boolean. '0', '0.0', '""', '"0"', 'null', and '[]' cast to 'false'; everything else casts to 'true'.
•
'(string)': Casts to string. 'true' becomes '"1"', 'false' becomes '""'.
•
'(array)': Converts scalar values into a 1-element array, or objects into an associative array of properties.
•
'(object)': Converts associative arrays into 'stdClass' objects.
Code Implementation Example
php
<?php
// 1. Array to stdClass Object casting
$userArr = ['name' => 'Alice', 'role' => 'admin'];
$userObj = (object)$userArr;
echo $userObj->name; // Outputs: Alice
// 2. String to Integer casting
echo (int)"42abc"; // Outputs 42 (stops at first non-digit)
// 3. Truthiness casting
var_dump((bool)"0"); // false
var_dump((bool)"false"); // true (non-empty string!)💡Explicit type casting between arrays, objects, strings, and booleans in PHP.
🎯 Interview Key Takeaway
Use explicit type casts ((int), (bool), (array), (object)) to reliably convert data types in PHP.
#Type Casting#Coercion#Data Types#Beginner
Back to all PHP 8+ Questions→