PHP Type Coversion Quiz

PHP
0 Passed
0% acceptance

A 35-question quiz focused on PHP type conversion strategies so you can juggle user input, database values, and API payloads without letting silent coercion hide bugs or security issues.

35 Questions
~70 minutes
1

Question 1

During an intake service review, why do senior engineers insist on casting incoming JSON fields to the expected types before passing them deeper into the application?

A
Explicit casting exposes malformed data immediately instead of letting PHP silently juggle it later.
B
Casting makes HTTP requests smaller.
C
Casting automatically encrypts the values.
D
Casting forces every request to use protobuf.
2

Question 2

A warehouse script trims counts from labels. What does this snippet echo?

php
<?php
$value = '12cases';
echo (int) $value;
?>
A
12
B
0
C
cases
D
12cases
3

Question 3

Support compared these two lines. Why do they log different values?

php
<?php
echo '5' + 4;
echo '5' . 4;
?>
A
The first produces 9 and the second produces 54 because + triggers numeric coercion while . concatenates strings.
B
Both lines output 9 because PHP always adds numbers first.
C
Both lines output 54 because PHP prefers strings.
D
The script throws a TypeError on the first line.
4

Question 4

Strict audits flagged a comparison using ==. Why is === safer when checking user roles stored as strings?

A
=== compares both type and value, preventing numeric strings like "0" from matching false or 0.
B
=== automatically trims whitespace.
C
=== encrypts the comparison result.
D
=== is faster than == in every case.
5

Question 5

A teammate wonders what FILTER_VALIDATE_INT returns. How does this snippet behave?

php
<?php
$result = filter_var('108', FILTER_VALIDATE_INT);
var_dump($result);
?>
A
int(108)
B
bool(true)
C
string(3) "108"
D
NULL
6

Question 6

During a design review, why do analysts recommend documenting expected array shapes using @var annotations such as @var array<int, string> $tags?

A
It lets IDEs and static analyzers catch wrong key/value types even though PHP lacks built-in generics.
B
It forces PHP to reindex arrays automatically.
C
It prevents the array from being serialized.
D
It encrypts the array data at rest.
7

Question 7

What does this optional parameter snippet echo for the fallback path?

php
<?php
$color = null;
$color ??= 'blue';
echo $color;
?>
A
blue
B
null
C
$color
D
TypeError
8

Question 8

A CLI importer wants to ensure a token contains only digits before casting. How does this snippet help?

php
<?php
echo ctype_digit('401A') ? 'ok' : 'reject';
?>
A
reject because ctype_digit fails when any non-digit appears
B
ok because hexadecimal digits are accepted
C
ok because uppercase letters are ignored
D
reject only when the string is empty
9

Question 9

When converting stored booleans, why is it risky to rely on the truthiness of strings like "false" without casting?

A
Any non-empty string evaluates to true, so "false" would still pass boolean checks unless you convert it explicitly.
B
"false" automatically becomes null.
C
Strings cannot be compared.
D
Strings always throw exceptions when cast to bool.
10

Question 10

New teammates compare json_decode outputs. What does this snippet display?

php
<?php
$payload = json_decode('{"active":true}', true);
var_dump($payload['active']);
?>
A
bool(true)
B
string(4) "true"
C
int(1)
D
NULL
11

Question 11

Why is number_format often used when showing floats to end users even though the internal value stays numeric?

A
It formats the number into a human-friendly string while leaving the underlying float untouched for calculations.
B
It converts the float into an array.
C
It forces the float to become an integer.
D
It permanently changes the stored value.
12

Question 12

A debugging session prints this snippet. What appears?

php
<?php
$value = 0.1 + 0.2;
echo (string) $value;
?>
A
0.30000000000000004
B
0.3
C
TypeError
D
0
13

Question 13

Security reviews often forbid using == when comparing hashed tokens. Why?

A
Loose comparisons can coerce certain crafted strings into matching unrelated hashes, bypassing checks.
B
== is slower than ===.
C
== always trims whitespace from hashes.
D
== automatically logs values to disk.
14

Question 14

A teammate checks how array_filter behaves with numeric strings. What prints?

php
<?php
$values = ['5', 5, '05'];
$filtered = array_filter($values, 'is_int');
print_r($filtered);
?>
A
Array ( [1] => 5 )
B
Array ( [0] => 5 [1] => 5 [2] => 05 )
C
Array ( )
D
Array ( [2] => 05 )
15

Question 15

When sanitizing query parameters, why is FILTER_SANITIZE_NUMBER_FLOAT with FILTER_FLAG_ALLOW_FRACTION useful?

A
It strips non-numeric characters while preserving digits, decimal points, and optional signs so the result can be safely cast.
B
It converts any string to int immediately.
C
It hashes the number for storage.
D
It enforces a currency format automatically.
16

Question 16

A code sample shows the risk of loose comparisons. What does it echo?

php
<?php
var_dump(0 == '0e12345');
?>
A
bool(true)
B
bool(false)
C
0e12345
D
TypeError
17

Question 17

Documentation for a typed DTO lists ?float $amount. What should reviewers infer from that declaration?

A
The property accepts either a float or null, so absence is a valid state the code must handle.
B
The property automatically casts to int.
C
The property can store strings implicitly.
D
The property is deprecated.
18

Question 18

What does this typed property snippet print?

php
<?php
class Invoice {
    public int $units;
}
$invoice = new Invoice();
$invoice->units = '5';
echo $invoice->units;
?>
A
5 after coercion
B
TypeError because the string cannot satisfy an int property when typed properties are strict
C
0
D
19

Question 19

Why do reviewers prefer explicit (float) casting before dividing integers when precise decimals are required?

A
Casting clarifies the intent to produce a floating-point result, avoiding accidental integer division in older code or reader confusion.
B
Casting disables division by zero errors.
C
Casting always speeds up the division.
D
Casting encrypts the output.
20

Question 20

A teammate tests bool casting. What prints here?

php
<?php
echo (bool) "0" ? 'true' : 'false';
?>
A
false
B
true
C
TypeError
D
0
21

Question 21

Why is intval($value, 16) preferred over (int)$value when parsing hexadecimal IDs from hardware devices?

A
intval can interpret the string according to the specified base, preventing letters A-F from terminating the parse early.
B
intval encrypts the result.
C
intval forces the output to stay a string.
D
intval only works on floats.
22

Question 22

A logging helper shows the risk of settype. What prints?

php
<?php
$value = 'status';
settype($value, 'int');
var_dump($value);
?>
A
int(0)
B
string(6) "status"
C
NULL
D
bool(false)
23

Question 23

When migrating legacy bool columns stored as "Y" or "N", why is a conversion map (e.g., ["Y" => true, "N" => false]) clearer than casting?

A
Mapping documents every accepted value explicitly and avoids relying on PHP truthiness rules.
B
Casting cannot process strings.
C
Maps automatically encrypt values.
D
Maps eliminate the need for tests.
24

Question 24

What does this sprintf-based conversion output?

php
<?php
$amount = 5;
echo sprintf('%.2f', $amount);
?>
A
5.00
B
5
C
0.05
D
TypeError
25

Question 25

During QA, why is it important to distinguish between JSON null and the string "null" when decoding payloads?

A
JSON null decodes to PHP null, whereas the string "null" remains a literal string and should not be treated as absence.
B
Both values map to bool(false).
C
JSON null converts to an empty array.
D
The decoder throws an exception for null.
26

Question 26

An onboarding kata highlights strtotime conversion. What does this snippet echo?

php
<?php
echo (string) strtotime('2025-01-01 00:00:00');
?>
A
An integer timestamp such as 1735689600
B
2025-01-01
C
TypeError
D
NULL
27

Question 27

Why do developers avoid storing resources (like cURL handles) in session data when discussing type conversion?

A
Resources cannot be serialized meaningfully; once outside the request, the handle no longer points to a valid external resource.
B
Resources always convert to floats.
C
Resources automatically expire after a millisecond.
D
Resources cannot be closed.
28

Question 28

A script compares integer input with a string reference. What prints?

php
<?php
$input = 10;
$reference = '10';
echo $input === $reference ? 'match' : 'mismatch';
?>
A
mismatch
B
match
C
10
D
TypeError
29

Question 29

When integrating with older XML services, why is simplexml_load_string often cast to JSON and back before further processing?

A
Converting to JSON/array simplifies type handling by turning SimpleXMLElement objects into predictable arrays or scalars.
B
Casting to JSON encrypts the payload.
C
XML cannot hold strings.
D
SimpleXML already returns arrays.
30

Question 30

Why does unpacking JSON into typed DTOs help with conversion discipline compared to using associative arrays everywhere?

A
DTOs enforce type declarations at construction, raising errors when payload values do not match the documented types.
B
DTOs automatically localize strings.
C
DTOs store dates as resources.
D
DTOs remove the need for validation.
31

Question 31

In a migration guide, why must teams differentiate between (array) $object and iterator_to_array($object) when converting traversable data?

A
(array) only exposes public properties, while iterator_to_array consumes the iterator to capture its elements.
B
(array) encrypts the iterator contents.
C
iterator_to_array returns JSON.
D
Both functions behave identically.
32

Question 32

Why is floatval() sometimes favored over (float)$value during refactors?

A
floatval conveys intent in a way some teams find more readable when scanning quick conversions.
B
floatval encrypts the result.
C
floatval only works on arrays.
D
floatval disables NaN values.
33

Question 33

A code review highlights bcadd usage. What type-related benefit does BCMath provide when summing currency as strings?

A
It performs decimal math with arbitrary precision, preventing binary rounding issues that arise with floats.
B
It automatically saves results to MySQL.
C
It casts the value to bool.
D
It converts strings to resources.
34

Question 34

A utility guards against double casting. What is the outcome of this snippet?

php
<?php
$value = (int) (float) '12.9';
echo $value;
?>
A
12
B
12.9
C
13
D
TypeError
35

Question 35

Why is it valuable to log both the original value and its cast form during complex imports?

A
Side-by-side logs show reviewers exactly how the conversion changed the data, making it easier to debug truncation or coercion issues.
B
Logs automatically reapply casts on retry.
C
Casting cannot be undone otherwise.
D
It reduces disk usage.

QUIZZES IN PHP