PHP automatically converts types when needed, like adding a number and a string.
PHP
<?php
$sum = 5 + "10"; // PHP converts string "10" to number 10
?>
Sample Program
This program shows how one variable changes type and how PHP converts types automatically.
PHP
<?php
$var = 7; // integerecho"Value: $var\n";
$var = "seven"; // stringecho"Value: $var\n";
$var = $var . " is a word."; // string concatenationecho"Value: $var\n";
$var = 3 + "4"; // PHP converts string to number and addsecho"Value: $var\n";
?>
OutputSuccess
Important Notes
Be careful: automatic type changes can cause unexpected results if you don't watch closely.
Use functions like gettype() to check a variable's type if unsure.
PHP dynamic typing helps speed up coding but requires attention to avoid bugs.
Summary
PHP variables do not need a declared type before use.
Variables can change type during the program.
PHP automatically converts types when needed in operations.
Practice
(1/5)
1. In PHP, what happens if you assign a string value to a variable and then assign an integer to the same variable later?
easy
A. PHP throws a type error because the variable type is fixed.
B. The variable keeps the original string type and ignores the integer.
C. The variable changes its type dynamically to integer.
D. The variable becomes an array containing both values.
Solution
Step 1: Understand PHP variable typing
PHP variables do not have fixed types and can change type dynamically during execution.
Step 2: Assign different types to the same variable
Assigning a string first and then an integer changes the variable's type to integer automatically.
Final Answer:
The variable changes its type dynamically to integer. -> Option C
Quick Check:
PHP variables are dynamically typed = B [OK]
Hint: Remember: PHP variables change type automatically when reassigned [OK]
Common Mistakes:
Thinking PHP variables have fixed types like in Java
Assuming PHP throws errors on type changes
Believing variables keep old values as arrays
2. Which of the following is the correct way to assign a float value to a variable in PHP?
easy
A. $num = 3.14; // float assignment
B. $num = '3.14'; // string assignment
C. $num = (int)3.14; // integer cast
D. $num = float(3.14); // float function
Solution
Step 1: Identify correct float assignment syntax
In PHP, assigning a float is done by directly assigning a number with decimal point without quotes.
Step 2: Evaluate each option
$num = 3.14; // float assignment assigns 3.14 as a float correctly. $num = '3.14'; // string assignment assigns a string, C casts to int, D uses invalid syntax.
Final Answer:
$num = 3.14; // float assignment -> Option A
Quick Check:
Float assignment uses decimal number without quotes = A [OK]
Hint: Assign floats without quotes; quotes make it a string [OK]
Common Mistakes:
Using quotes around numbers to assign floats
Trying to cast with invalid functions like float()
Casting floats to int unintentionally
3. What will be the output of the following PHP code?