0
0
PHPprogramming~20 mins

Compact and extract functions in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Compact & Extract Master
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 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);
?>
AArray ( [name] => 0 [age] => 0 )
BArray ( [0] => name [1] => age )
CArray ( [name] => 'name' [age] => 'age' )
DArray ( [name] => Alice [age] => 30 )
Attempts:
2 left
💡 Hint
The compact function creates an array using variable names as keys and their values as values.
Predict Output
intermediate
2: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";
?>
AParis, France
Bcity, country
CArray, Array
DUndefined variable error
Attempts:
2 left
💡 Hint
extract() creates variables from array keys with their corresponding values.
🔧 Debug
advanced
2: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";
?>
ABecause $dup_name is not created if no conflict exists
BBecause variables $name and $age already exist before extract()
CBecause EXTR_PREFIX_SAME requires a prefix but none is given
DBecause extract() cannot handle arrays with string keys
Attempts:
2 left
💡 Hint
EXTR_PREFIX_SAME adds prefix only if variable name conflicts with existing variables.
🧠 Conceptual
advanced
2: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";
?>
A10, 20
B1, 2
CUndefined variable error
D0, 0
Attempts:
2 left
💡 Hint
EXTR_SKIP prevents overwriting existing variables.
Predict Output
expert
2: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.";
?>
AJohn Doe is years old.
BJohn Doe is 40 years old.
CJohn Doe is 50 years old.
DUndefined variable error
Attempts:
2 left
💡 Hint
extract() creates variables from the compacted array, but $age is changed after extract().