PHP Type Casting and Type Juggling Practice Questions with Solutions

Introduction

PHP supports automatic and manual conversion between data types. Type juggling happens when PHP automatically converts a value from one type to another, while type casting allows you to convert a value to a specific type manually. These concepts are important when handling form inputs, calculating prices, comparing values, and working with databases. In this chapter, you will practice both concepts with PHP examples. PHP Type Casting and Type Juggling Practice Questions with Solutions to help you understand the concepts.

Question 1: Convert a String into an Integer

Problem Statement: Create a variable containing the string "250". Convert it into an integer and display its value and data type.

PHP Solution:

<?php
$price = "250";

$convertedPrice = (int) $price;

echo "Original Value: " . $price . "<br>";
echo "Converted Value: " . $convertedPrice . "<br>";

var_dump($convertedPrice);
?>

Sample Output:

Original Value: 250
Converted Value: 250
int(250)

Explanation: The value "250" is originally a string. The (int) cast converts it into an integer. This is an example of manual type casting.

Concepts Covered: String, integer, explicit type casting.

Question 2: Convert a String into a Float

Problem Statement: A product price is stored as the string "1499.75". Convert it into a float and add a delivery charge of 50.

PHP Solution:

<?php
$productPrice = "1499.75";

$productPrice = (float) $productPrice;
$deliveryCharge = 50;

$totalAmount = $productPrice + $deliveryCharge;

echo "Product Price: " . $productPrice . "<br>";
echo "Delivery Charge: " . $deliveryCharge . "<br>";
echo "Total Amount: " . $totalAmount;
?>

Sample Output:

Product Price: 1499.75
Delivery Charge: 50
Total Amount: 1549.75

Explanation: The (float) cast converts the numeric string into a floating-point number. PHP can then perform the addition correctly.

Concepts Covered: Float casting, arithmetic operations, numeric strings.

Question 3: Convert an Integer into a String

Problem Statement: Store an employee ID as an integer. Convert it into a string and display its data type.

PHP Solution:

<?php
$employeeID = 105;

$employeeIDText = (string) $employeeID;

echo "Employee ID: " . $employeeIDText . "<br>";
echo "Data Type: ";

var_dump($employeeIDText);
?>

Sample Output:

Employee ID: 105
Data Type: string(3) "105"

Explanation: The (string) cast converts the integer 105 into the string "105". This can be useful when preparing values for text processing or display.

Concepts Covered: String casting, integers, var_dump().

Question 4: Convert a Float into an Integer

Problem Statement: A product costs 799.95. Convert its price into an integer and display both values.

PHP Solution:

<?php
$productPrice = 799.95;

$wholePrice = (int) $productPrice;

echo "Original Price: " . $productPrice . "<br>";
echo "Integer Price: " . $wholePrice;
?>

Sample Output:

Original Price: 799.95
Integer Price: 799

Explanation: Casting a positive float to an integer removes the fractional part rather than rounding to the nearest whole number. For example, 799.95 becomes 799.

Concepts Covered: Float-to-integer casting, truncation.

Question 5: Understand Automatic Type Juggling in Addition

Problem Statement: Store "100" as a string and 50 as an integer. Add them and check the result’s data type.

PHP Solution:

<?php
$firstValue = "100";
$secondValue = 50;

$result = $firstValue + $secondValue;

echo "Result: " . $result . "<br>";
echo "Result Type: ";

var_dump($result);
?>

Sample Output:

Result: 150
Result Type: int(150)

Explanation: PHP recognizes "100" as a numeric string and converts it for the arithmetic operation. Since both values represent whole numbers, the result is an integer. This automatic conversion is called type juggling.

Concepts Covered: Automatic conversion, numeric strings, arithmetic.

Question 6: Understand Automatic Conversion in Comparisons

Problem Statement: Compare the integer 25 with the numeric string "25" using both == and ===.

PHP Solution:

<?php
$number = 25;
$textNumber = "25";

echo "Loose Comparison: ";
var_dump($number == $textNumber);

echo "Strict Comparison: ";
var_dump($number === $textNumber);
?>

Sample Output:

Loose Comparison: bool(true)
Strict Comparison: bool(false)

Explanation: The == operator compares values after any applicable type conversion. The === operator requires both the value and data type to match. Because one value is an integer and the other is a string, strict comparison returns false.

Concepts Covered: Type juggling, loose comparison, strict comparison.

Question 7: Convert a String into a Boolean

Problem Statement: Convert the string "Hello" into a Boolean and check the result. Then convert the string "0" into a Boolean.

PHP Solution:

<?php
$text1 = "Hello";
$text2 = "0";

$value1 = (bool) $text1;
$value2 = (bool) $text2;

echo "Hello as Boolean: ";
var_dump($value1);

echo "String 0 as Boolean: ";
var_dump($value2);
?>

Sample Output:

Hello as Boolean: bool(true)
String 0 as Boolean: bool(false)

Explanation: Most non-empty strings convert to true. However, the empty string "" and the string "0" convert to false. This distinction is useful when checking form values and flags.

Concepts Covered: Boolean casting, truthy and falsy values.

Question 8: Convert a Numeric String before Calculating a Salary

Problem Statement: An employee’s basic salary is stored as "30000" and the allowance as "5000". Convert both values into numbers and calculate the total salary.

PHP Solution:

<?php
$basicSalary = "30000";
$allowance = "5000";

$basicSalary = (int) $basicSalary;
$allowance = (int) $allowance;

$totalSalary = $basicSalary + $allowance;

echo "Basic Salary: " . $basicSalary . "<br>";
echo "Allowance: " . $allowance . "<br>";
echo "Total Salary: " . $totalSalary;
?>

Sample Output:

Basic Salary: 30000
Allowance: 5000
Total Salary: 35000

Explanation: Both salary values are explicitly converted to integers before addition. This makes the intended data types clear and helps when preparing data for calculations. In real applications, validate input before casting it.

Concepts Covered: Type casting, salary calculations, numeric input.

Question 9: Understand Type Juggling with a Numeric String and a Non-Numeric String

Problem Statement: Add the numeric string "20" to the non-numeric string "Hello" and observe the result in PHP 8 or later.

PHP Solution:

<?php
$number = "20";
$text = "Hello";

echo $number + $text;
?>

Expected Result:

Fatal error: Uncaught TypeError

Explanation: In PHP 8 and later, adding a numeric string to a non-numeric string throws a TypeError. PHP does not treat "Hello" as the number zero for this arithmetic operation. Always validate data before performing calculations.

Concepts Covered: Numeric strings, non-numeric strings, TypeError, input validation.

Question 10: Compare Automatic Conversion with Manual Type Casting

Problem Statement: Store "45" as a string and 5 as an integer. Calculate the sum once using PHP’s automatic conversion and once after explicitly casting the string to an integer.

PHP Solution:

<?php
$value = "45";
$number = 5;

// Automatic type juggling
$automaticResult = $value + $number;

// Manual type casting
$convertedValue = (int) $value;
$manualResult = $convertedValue + $number;

echo "Automatic Result: " . $automaticResult . "<br>";
echo "Manual Result: " . $manualResult . "<br>";

echo "Automatic Result Type: ";
var_dump($automaticResult);

echo "Manual Result Type: ";
var_dump($manualResult);
?>

Sample Output:

Automatic Result: 50
Manual Result: 50
Automatic Result Type: int(50)
Manual Result Type: int(50)

Explanation: Both calculations produce the same result because PHP automatically recognizes "45" as a numeric string in the arithmetic operation. Manual casting explicitly converts the value before the calculation, making your intention clearer.

Concepts Covered: Type juggling, explicit casting, arithmetic operations.

Key Takeaways

  • Type casting means manually converting a value into another data type.
  • Type juggling means PHP automatically converts types when an operation allows it.
  • (int), (float), (string) and (bool) are common casting forms.
  • Casting a float to an integer removes its fractional part; it does not round it.
  • Numeric strings can be used in arithmetic operations when PHP recognizes them as numeric.
  • The == operator allows applicable type conversions, while === checks both type and value.
  • Most non-empty strings convert to true, but "0" converts to false.
  • Invalid input should be validated before casting or calculating.
  • PHP 8 and later can throw a TypeError when arithmetic uses a non-numeric string.

Frequently Asked Questions (FAQs)

1. What is type casting in PHP?

Type casting is the manual conversion of a value from one data type to another, such as converting "100" into the integer 100 using (int).

2. What is type juggling in PHP?

Type juggling is PHP’s automatic conversion of values between data types when an operation permits it.

3. What is the difference between type casting and type juggling?

Type casting is explicitly requested by the programmer. Type juggling occurs automatically according to PHP’s rules for a particular operation.

4. How do you convert a string into an integer in PHP?

Use the integer cast:

$value = "150";
$number = (int) $value;

For untrusted input, validate the value before converting it.

5. Does converting a float into an integer round the value?

No. Casting 12.9 to an integer produces 12, not 13. Use round() when rounding is required.

6. What happens when a numeric string is added to an integer?

PHP generally recognizes a valid numeric string and uses its numeric value in the arithmetic operation.

7. What happens when you convert "Hello" into an integer?

A direct integer cast of a non-numeric string such as "Hello" produces 0. Do not rely on this behavior to validate user input.

8. Why does "0" become false when cast to Boolean?

PHP treats the string "0" as a falsy value. Most other non-empty strings convert to true.

9. What is the difference between == and ===?

== checks equality with applicable type conversion, while === requires the values to have the same data type and value.

10. Why should we learn type casting and type juggling?

These concepts help you handle form inputs, salary calculations, prices, comparisons, and database values correctly.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top