PHP Data Types Overview Quiz

PHP
0 Passed
0% acceptance

A 40-question quiz covering how PHP represents scalars, arrays, objects, enums, and resources so teams can reason about conversions, validation, and storage when values move through an application.

40 Questions
~80 minutes
1

Question 1

While preparing an orientation card for new hires, which list contains only PHP scalar types they will handle on their first week?

A
Integers, floats, strings, booleans
B
Arrays, objects, resources, null
C
Integers, arrays, traits, strings
D
Enums, iterables, resources, references
2

Question 2

A build pipeline logs this snippet while checking an import; what does it display?

php
<?php
$value = "42";
$value += 8;
var_dump($value);
?>
A
int(50)
B
string(2) "42"
C
string(3) "508"
D
float(50)
3

Question 3

Product analytics needs reassurance that counters remain exact. Why are integers the preferred storage for page-view totals?

A
Integers represent whole numbers exactly without binary rounding surprises.
B
Integers automatically persist to disk between requests.
C
Integers always consume less memory than floats.
D
Integers cannot exceed 32-bit boundaries.
4

Question 4

A teammate enables strict typing before this helper to stabilize metrics. What happens when it runs?

php
<?php
declare(strict_types=1);

function sumIntegers(int $a, int $b): int {
    return $a + $b;
}

echo sumIntegers('3', 2);
?>
A
It echoes 5 after silently coercing the string.
B
It throws a TypeError because the string cannot satisfy the int parameter.
C
It echoes 32 because the arguments are concatenated.
D
It returns null and continues silently.
5

Question 5

A support dashboard compares the string "007" with the number 7. Which operator keeps them distinct so the alert only fires on truly identical values?

A
===
B
==
C
<>
D
=
6

Question 6

QA shares this snippet to illustrate floating-point behavior. What does it output?

php
<?php
$score = 0.1 + 0.2;
var_dump($score === 0.3);
?>
A
bool(true)
B
bool(false)
C
0.3
D
0.30000000000000004
7

Question 7

Finance automation stores invoice totals as strings and uses BCMath for arithmetic. Why choose this pattern over plain floats?

A
BCMath performs decimal math in base 10, preventing cumulative rounding errors with cents.
B
Floats cannot be sent over HTTP.
C
Strings consume less space than floats.
D
BCMath disables currency conversions.
8

Question 8

A logging helper prints the type of incoming payloads. What does this snippet echo?

php
<?php
$data = ['status' => 'draft'];
echo get_debug_type($data);
?>
A
array
B
object
C
hashmap
D
callable
9

Question 9

Architecture guidelines mention compound types. Which PHP values fall into that family?

A
Arrays, objects, callables, and iterables that bundle multiple values.
B
Integers and floats only.
C
Booleans paired with strings.
D
Resources and null only.
10

Question 10

During an API debug session, what type does json_decode return by default for JSON objects?

php
<?php
$result = json_decode('{"count":5}');
echo gettype($result);
?>
A
object
B
array
C
string
D
resource
11

Question 11

A docstring marks a parameter as mixed. What does that communicate to anyone calling the function?

A
The parameter can accept any PHP type, so the function must handle flexible input.
B
Only integers are allowed but the docstring is outdated.
C
The value is automatically cast to an array.
D
The parameter is deprecated.
12

Question 12

A migration script uses settype to normalize seat counts. What does it echo?

php
<?php
$value = '9 seats';
settype($value, 'int');
echo $value;
?>
A
9
B
9 seats
C
0
D
Notice: settype failed
13

Question 13

When documentation references a resource type, what does that label mean in PHP?

A
A special handle that points to an external system such as a file, socket, or stream.
B
A magic number stored in RAM.
C
A serialized array with metadata.
D
A namespace alias for constants.
14

Question 14

Ops opened a temporary memory stream to test logging. What does var_dump show?

php
<?php
$handle = fopen('php://memory', 'r');
var_dump($handle);
?>
A
resource(#) of type (stream)
B
object(stdClass)
C
string(6) "stream"
D
bool(false)
15

Question 15

A job queue stores callbacks for retries. Why does the interface demand that each entry be callable?

A
Marking the type as callable guarantees the dispatcher can invoke it without extra reflection.
B
Callable values serialize faster than strings.
C
Databases reject rows without callable types.
D
Callable variables cannot throw exceptions.
16

Question 16

A teammate checks whether arrow functions satisfy the callable contract. What does this snippet output?

php
<?php
$handler = fn (int $n): int => $n * 2;
var_dump(is_callable($handler));
?>
A
bool(true)
B
bool(false)
C
0
D
TypeError
17

Question 17

Why do typed properties on DTOs make code reviews calmer when discussing expected data types?

A
Assignments that violate the declared type fail immediately, surfacing mismatches before values travel further.
B
Typed properties automatically encrypt values.
C
Typed properties turn every property into an array.
D
They disable constructor requirements.
18

Question 18

The data platform introduces a union-typed normalizer. What gets printed?

php
<?php
class Normalizer {
    public function magnitude(int|float $value): float {
        return abs($value);
    }
}
echo (new Normalizer())->magnitude(-4.5);
?>
A
-4.5
B
4.5
C
TypeError: value must be int
D
0
19

Question 19

A profile form stores an optional nickname. Why would the DTO declare the property as ?string instead of plain string?

A
The question mark allows the value to be null when the user leaves it blank, making the optional intent explicit.
B
The question mark converts strings to integers.
C
Nullable strings automatically persist to Redis.
D
The question mark forces the property to be required.
20

Question 20

A DTO starts with a null typed property and relies on a fallback. What does this snippet echo?

php
<?php
class ToggleDTO {
    public ?bool $enabled = null;
}
$dto = new ToggleDTO();
echo $dto->enabled ?? 'unset';
?>
A
1
B
C
unset
D
TypeError
21

Question 21

Why would a team choose SplFixedArray when modelling a week of hourly samples?

A
It enforces integer indexes and a fixed size, making type expectations around the collection explicit.
B
It automatically casts every value to a float.
C
It encrypts the contents at rest.
D
It turns each slot into an object.
22

Question 22

A legacy API expects arrays, so a teammate casts an object first. What does the printout look like?

php
<?php
$user = (object) ['name' => 'Lea'];
print_r((array) $user);
?>
A
Array with [name] => Lea
B
stdClass Object ( [name] => Lea )
C
name=Lea
D
object(Lea)
23

Question 23

Product managers defined a closed list of publishing phases. How do enums help with data types in this situation?

A
Enums encode the allowed values inside the type system so invalid strings cannot sneak through.
B
Enums automatically persist to CSV files.
C
Enums make every property nullable.
D
Enums guarantee faster JSON encoding.
24

Question 24

A backed enum powers deployment gates. What does this snippet echo?

php
<?php
enum Phase: string {
    case Draft = 'draft';
    case Live = 'live';
}
echo Phase::Live->value;
?>
A
live
B
Phase::Live
C
Phase
D
1
25

Question 25

Input validation uses filter_var($input, FILTER_VALIDATE_INT). What makes this helpful for data types?

A
The filter returns an int on success and false on failure, letting you distinguish valid numeric input from junk.
B
It converts any string into a float automatically.
C
It sanitizes HTML tags out of the value.
D
It enforces currency symbols.
26

Question 26

A warehouse script checks SKU strings before casting. What prints?

php
<?php
echo ctype_digit('042') ? 'digits' : 'mixed';
?>
A
digits
B
mixed
C
042
D
bool(false)
27

Question 27

A CLI importer reads hexadecimal identifiers. When would intval($token, 16) be preferred over a simple (int)$token cast?

A
When the string is expressed in a base other than 10 and must be interpreted accordingly.
B
When you need to encrypt the string.
C
When the string already holds a decimal number.
D
When you want to force the value to stay a string.
28

Question 28

An ETL step casts a label before storing it. What echoes to the console?

php
<?php
$value = (int) '15apples';
echo $value;
?>
A
15
B
0
C
apples
D
15apples
29

Question 29

A permission check uses in_array($role, $allowed, true). Why insist on the strict flag?

A
The third argument forces type-safe comparisons so "0" does not equal 0 or false.
B
The strict flag sorts the array before searching.
C
The strict flag speeds up network calls.
D
The strict flag converts results to uppercase.
30

Question 30

A data-cleaning pass keeps only integers from a mixed array. What does it print?

php
<?php
$values = ['3', 'level', 2];
$result = array_filter($values, 'is_int');
print_r($result);
?>
A
Array ( [2] => 2 )
B
Array ( [0] => 3 [2] => 2 )
C
Array ( )
D
Array ( [0] => level )
31

Question 31

Why might a scheduling module favor DateTimeImmutable over DateTime for representing appointments?

A
Immutable objects force every adjustment to return a new instance, preventing accidental in-place mutation of shared values.
B
Immutable objects automatically serialize to JSON.
C
Immutable objects are always faster.
D
DateTimeImmutable cannot represent time zones.
32

Question 32

A monitoring script classifies values by type. What does it echo?

php
<?php
$value = 5.5;
echo match (get_debug_type($value)) {
    'int' => 'whole',
    'float' => 'decimal',
    default => 'other'
};
?>
A
whole
B
decimal
C
other
D
float
33

Question 33

Log aggregation recently switched from gettype to get_debug_type. What advantage does the newer helper provide when diagnosing data mismatches?

A
get_debug_type reports class names and union information, offering more precise descriptions than the older helper.
B
It encrypts the log output automatically.
C
It removes sensitive fields from arrays.
D
It stops scripts once a type mismatch occurs.
34

Question 34

During API design, why differentiate between null and an empty string when representing an optional nickname?

A
null communicates "no value provided," while an empty string means the user intentionally supplied blank text.
B
They are interchangeable so there is no reason.
C
Empty strings crash JSON encoding.
D
null cannot be stored in databases.
35

Question 35

When normalizing boolean toggles from HTML forms, why use filter_var with FILTER_VALIDATE_BOOL and FILTER_NULL_ON_FAILURE?

A
It converts recognized truthy strings into actual bool values while returning null for anything ambiguous, so you can handle mistakes explicitly.
B
It hashes the string for security.
C
It forces the result to remain a string.
D
It automatically stores the result in the session.
36

Question 36

Static analysis rules request docblocks such as @var array<int, string>. How does that help with data types?

A
It documents the expected key and value types inside arrays so tools can flag mismatches even though PHP itself does not enforce generics.
B
It automatically reorders arrays.
C
It makes arrays immutable.
D
It encrypts array contents.
37

Question 37

Finance code wraps raw integers inside a Money value object. What benefit does that bring to type handling?

A
The value object couples the amount with its currency and rules, preventing plain integers from being misused outside their context.
B
It increases database throughput automatically.
C
It removes the need for validation.
D
It forces every property to become public.
38

Question 38

A DTO marks several properties as readonly. How does that choice relate to data-type safety?

A
Readonly typed properties can only be assigned once, ensuring the value's type and meaning stay locked after construction.
B
Readonly automatically casts values to arrays.
C
Readonly removes the need for type declarations.
D
Readonly forces values to become resources.
39

Question 39

Why do architects discourage storing resources or open stream handles inside sessions or caches?

A
Resources refer to external processes that cannot be serialized or restored later, so the handle becomes invalid outside the current request.
B
Resources automatically trigger garbage collection pauses.
C
Resources convert to JSON better than arrays.
D
Resources always point to SQLite databases.
40

Question 40

An ingestion Lambda receives numeric strings from partners. Why cast them to int or float before arithmetic even if PHP would juggle them automatically?

A
Explicit casts document the intended type, trigger validation when the string is malformed, and prevent hidden coercions from turning "1e3" or "0x10" into surprising values.
B
Casts encrypt the payload.
C
Casts make the code run on older PHP versions.
D
Casts keep the value as a string forever.

QUIZZES IN PHP