Skip to Content
Course content

123: Compact and Extract Functions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why would I use compact() instead of just building an array manually?

I've seen a lot of developers write out associative arrays like this: $data = ['name' => $name, 'email' => $email, 'role' => $role];. It's explicit, sure, but it's tedious and repetitive. If you have five or six variables, you're just typing the same names twice.

compact() is your shortcut. It looks for variables in the current symbol table that match the strings you pass into it and builds the array for you. Here is how I'd handle a user profile setup:

$userName = 'jdoe_dev';
$userEmail = 'jane@example.com';
$userStatus = 'Active';

// Instead of the long way, just do this:
$userProfile = compact('userName', 'userEmail', 'userStatus');

print_r($userProfile); 
/* 
Output: 
Array ( 
  [userName] => jdoe_dev 
  [userEmail] => jane@example.com 
  [userStatus] => Active 
) 
*/

It's a huge time-saver, especially when you're passing a bunch of local variables into a template rendering function or a view helper.

How does extract() work and when is it actually useful?

If compact() is the "packer," extract() is the "unpacker." It takes an associative array and imports the keys as variable names. It's essentially the inverse of the first function we talked about.

You'll see this most often in custom template engines or configuration loaders. Imagine you've fetched a row from a database as an array, but you want to use those values as standalone variables in your HTML template to keep the code clean.

$productData = [
    'title' => 'Mechanical Keyboard',
    'price' => 120.00,
    'stock' => 15
];

extract($productData);

// Now I can use $title, $price, and $stock directly
echo "The {$title} costs ${$price}. We have {$stock} left.";

I'll be honest: it feels like magic, and in software, "magic" can sometimes be a red flag. But when used for a clean separation between your logic and your presentation layer, it's very effective.

Is there a catch to using extract()?

Yes, a big one. You have to be extremely careful about where the array comes from. If you extract($_POST) or extract($_GET), you are letting a user create variables inside your script. If you already had a variable called $isAdmin set to false, and a user sends ?isAdmin=1 in the URL, extract() will overwrite your security check.

To prevent this, PHP provides flags. I always recommend using EXTR_SKIP if you're not 100% sure about the source of the data. This tells PHP: "If the variable already exists, don't touch it."

$isAdmin = false;
$userData = ['isAdmin' => true, 'nickname' => 'Hacker123'];

// Use EXTR_SKIP to protect existing variables
extract($userData, EXTR_SKIP);

echo $isAdmin ? 'Admin access' : 'Standard user'; 
// Output: Standard user (the array didn't overwrite our boolean)

Basically, use compact() as much as you like, but treat extract() with a bit of healthy suspicion.




📋 Practical Task

Exercise: Building a Product Detail Page Data Bridge

You are building a simple product display system. You have a set of individual variables representing a product, but your renderProductPage() function requires a single array as an argument. Once inside that function, you want to unpack that array back into variables for easier printing.

Your Task:

  • Create three variables: $productName, $productPrice, and $productSku.
  • Use compact() to wrap these three variables into a single array called $productBundle.
  • Define a function renderProductPage($data). Inside this function:
    • Use extract() on the $data array.
    • Print a string using the extracted variables (e.g., "Product: [name], SKU: [sku], Price: [price]").
  • Call the function and pass in your $productBundle.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.