This program shows how compact groups variables into an array, and extract creates variables back from that array.
PHP
<?php
// Define variables
$firstName = "John";
$lastName = "Doe";
$age = 30;
// Use compact to create an array from variables
$userData = compact('firstName', 'lastName', 'age');
// Show the arrayprint_r($userData);
// Now extract variables back from the array
extract($userData);
// Use the extracted variablesecho"Name: $firstName $lastName\n";
echo"Age: $age\n";
?>
OutputSuccess
Important Notes
Be careful with extract as it can overwrite existing variables if keys match.
You can use flags with extract to control how variables are created, like adding prefixes.
Summary
compact turns variables into an array using their names.
extract turns array keys into variables with their values.
These functions help organize and reuse data easily.
Practice
(1/5)
1. What does the PHP function compact do?
easy
A. Creates an array from given variable names and their values
B. Extracts variables from an array into the current symbol table
C. Deletes variables from the current scope
D. Converts an array into a JSON string
Solution
Step 1: Understand the purpose of compact
The compact function takes variable names as strings and creates an associative array where keys are those names and values are the variables' values.
Step 2: Differentiate from extract
extract does the opposite by creating variables from array keys, so it is not the correct description for compact.
Final Answer:
Creates an array from given variable names and their values -> Option A
Quick Check:
compact = array from variables [OK]
Hint: Remember: compact packs variables into an array [OK]
Common Mistakes:
Confusing compact with extract
Thinking compact extracts variables
Assuming compact converts arrays to strings
2. Which of the following is the correct syntax to use extract on an array $data?
easy
A. extract = $data;
B. extract($data);
C. extract->$data();
D. extract($data[]);
Solution
Step 1: Recall the function call syntax
In PHP, functions are called by their name followed by parentheses containing arguments. So extract($data); is the correct syntax.
Step 2: Identify incorrect syntax
Options B, C, and D misuse assignment, object operator, or array syntax, which are invalid for function calls.
Final Answer:
extract($data); -> Option B
Quick Check:
Function call syntax = extract($data); [OK]
Hint: Use parentheses to call extract with array argument [OK]