0
0
PHPprogramming~20 mins

Settype for changing types in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Settype Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP code using settype?

Consider the following PHP code snippet:

$var = '123abc';
settype($var, 'int');
echo $var;

What will be printed?

PHP
$var = '123abc';
settype($var, 'int');
echo $var;
A123
B0
C123abc
DError
Attempts:
2 left
💡 Hint

When converting a string to int, PHP reads the number from the start until it hits a non-digit.

Predict Output
intermediate
2:00remaining
What is the output after changing type to boolean?

What will this PHP code print?

$value = 0;
settype($value, 'bool');
echo $value ? 'true' : 'false';
PHP
$value = 0;
settype($value, 'bool');
echo $value ? 'true' : 'false';
Atrue
Bfalse
C0
D1
Attempts:
2 left
💡 Hint

Remember that 0 is considered false in boolean context.

Predict Output
advanced
2:00remaining
What is the output when converting an array to string with settype?

Analyze this PHP code:

$arr = [1, 2, 3];
settype($arr, 'string');
echo $arr;

What will it output?

PHP
$arr = [1, 2, 3];
settype($arr, 'string');
echo $arr;
AError
B1,2,3
CArray
DArrayObject
Attempts:
2 left
💡 Hint

When converting an array to string, PHP returns a fixed word.

Predict Output
advanced
2:00remaining
What error does this code raise when using settype with an invalid type?

Consider this PHP code:

$var = 5;
settype($var, 'unknown');

What happens when this runs?

PHP
$var = 5;
settype($var, 'unknown');
ANo error, $var remains unchanged
BParse error
CFatal error: Unknown type
DWarning: settype() expects parameter 2 to be string of valid type
Attempts:
2 left
💡 Hint

PHP warns if the type string is not recognized.

🧠 Conceptual
expert
3:00remaining
How many items are in the array after this settype operation?

What is the count of elements in $data after this code runs?

$data = '1,2,3';
settype($data, 'array');
$count = count($data);
echo $count;
PHP
$data = '1,2,3';
settype($data, 'array');
$count = count($data);
echo $count;
A1
B3
C0
DError
Attempts:
2 left
💡 Hint

Converting a string to array with settype wraps it inside an array.