Challenge - 5 Problems
Compact & Extract Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP code using compact?
Consider the following PHP code snippet. What will be the output when it runs?
PHP
<?php $name = 'Alice'; $age = 30; $info = compact('name', 'age'); print_r($info); ?>
Attempts:
2 left
💡 Hint
The compact function creates an array using variable names as keys and their values as values.
✗ Incorrect
The compact function takes variable names as strings and returns an associative array where keys are those names and values are the variables' values.
❓ Predict Output
intermediate2:00remaining
What does extract() do in this PHP code?
Look at this PHP code. What will be the output after running it?
PHP
<?php $data = ['city' => 'Paris', 'country' => 'France']; extract($data); echo "$city, $country"; ?>
Attempts:
2 left
💡 Hint
extract() creates variables from array keys with their corresponding values.
✗ Incorrect
extract() takes keys from the array and creates variables with those names, assigning the array values to them.
🔧 Debug
advanced2:00remaining
Why does this extract() call cause a warning?
This PHP code produces a warning. What is the cause?
PHP
<?php $info = ['name' => 'Bob', 'age' => 25]; extract($info, EXTR_PREFIX_SAME, 'dup'); echo "$name, $age, $dup_name"; ?>
Attempts:
2 left
💡 Hint
EXTR_PREFIX_SAME adds prefix only if variable name conflicts with existing variables.
✗ Incorrect
Since $name and $age do not exist before extract(), no conflict occurs, so no prefixed variables like $dup_name are created.
🧠 Conceptual
advanced2:00remaining
What happens if extract() is used with EXTR_SKIP and variables exist?
Given existing variables $a = 1 and $b = 2, and array ['a' => 10, 'b' => 20], what will be the values of $a and $b after extract() with EXTR_SKIP?
PHP
<?php $a = 1; $b = 2; $arr = ['a' => 10, 'b' => 20]; extract($arr, EXTR_SKIP); echo "$a, $b"; ?>
Attempts:
2 left
💡 Hint
EXTR_SKIP prevents overwriting existing variables.
✗ Incorrect
EXTR_SKIP tells extract() to skip variables that already exist, so $a and $b keep their original values.
❓ Predict Output
expert2:00remaining
What is the output of this combined compact and extract example?
Analyze this PHP code and determine the output printed.
PHP
<?php $first = 'John'; $last = 'Doe'; $age = 40; $person = compact('first', 'last'); extract($person); $age = 50; echo "$first $last is $age years old."; ?>
Attempts:
2 left
💡 Hint
extract() creates variables from the compacted array, but $age is changed after extract().
✗ Incorrect
compact() creates an array with 'first' and 'last'. extract() creates variables $first and $last. $age is not included in compact, so the later assignment $age = 50 is used in echo.