PHP compact Function: Assoc Array from Variables

PHP Compact Function

The PHP compact function is a way to pull variables into an array. In this article, you will learn how it works with examples.

What is compact() in PHP?

The compact() function in PHP builds an array using variable names you give it as strings.

PHP checks if those variables exist in the current scope. If they do, it adds them to the array with the variable name as the key and its value as the value.

Here is the syntax:

compact(VARIABLE_NAME, VARIABLE_NAME, ...)
  • You can pass any number of arguments to compact().
  • Each argument must be either a string or an array of strings.
  • PHP combines them all into one result array.

Here is a quick example:

$title = "Home Page";
$user = "Tarek";

$assoc_arr = compact("title", "user");
print_r($assoc_arr);

Output:

Array
(
[title] => Home Page
[user] => Tarek
)

Don’t use the compact() function if the variable names are unclear or if your array needs custom keys. Also, skip it if you need to validate or format values before storing them in an array.

Here are its limitation:

  • Does not support variable values.
  • Does not handle nested arrays or nested variable names.

Let’s move on to the following section to understand how PHP compact works with an array in PHP.

How to Compact an Array in PHP

You can use an array instead of variable names as a parameter like this:

$name = 'Khaldon';
$age = '25 years';
$vars = ['name', 'age'];
$data = compact($vars);
print_r($data);

Output:

Array
(
[name] => Khaldon
[age] => 25 years
)

You can also mirge variables with array of variable names:

$name = 'Yaseen Noor';
$age = '25 years';
$country = 'Germany';
$base = ['country'];
$result = compact($base, 'name', 'age');
print_r($result);

Output:

Array
(
[country] => Germany
[name] => Yaseen Noor
[age] => 25 years
)

So, why you can’t use compact(['key' => 'value'])?

The compact() expects variable names as strings (or arrays of strings). It does not accept associative arrays like 'key' => 'value'. So, in this example, it will only look for the variable $value.

PHP Compact Examples

Variable not defined:

$name = 'Mike';

$result = compact('name', 'email');  
print_r($result);

It will show you the following result:

Array
(
[name] => Mike
)

PHP Warning: compact(): Undefined variable $email in /HelloWorld.php on line 3

compact() skips variables that are not defined.

Merge with an existing array:

$name = 'Sara';
$age = 22;
$base = ['country' => 'USA'];

$result = array_merge($base, compact('name', 'age'));
print_r($result);

Output:

Array
(
[country] => USA
[name] => Sara
[age] => 22
)

Wrapping Up

In this tutorial, you learned how PHP’s compact() function works and how to use it with variables and arrays. You also saw what it can and cannot do through clear examples.

Here’s a quick recap:

  • compact() builds an associative array using variable names as keys and their values.
  • It accepts strings or arrays of strings as arguments.
  • It skips undefined variables without throwing an error.
  • You can merge variables and arrays of variable names together using compact(...).
  • It doesn’t support associative arrays like ['key' => 'value'].
  • Use it only when your variable names are clear and require no extra formatting.

Thank you for reading. If you want to read more PHP articles, click here.

FAQ’s

What does compact() do in PHP?

compact() creates an associative array using variable names as keys and their current values as values. It checks if each variable exists and includes it in the array if it does

What is the syntax of compact() in PHP?

compact('var1', 'var2', ...);
You can also pass arrays of variable names:
compact(['var1', 'var2'], 'var3');

Can I use compact() with arrays?

Yes. You can pass an array of variable names:
$name = 'Khaldon';
$age = '25 years';
$vars = ['name', 'age'];
$data = compact($vars);

What happens if a variable does not exist?

compact() skips any undefined variable without stopping the script. It shows a warning but still builds the array:
$name = 'Mike';
$result = compact('name', 'email');
// Only 'name' will be included

Similar Reads

PHP array_intersect_key Function: How it Works with Examples

The array_intersect_key in PHP compares arrays by keys and returns only the parts that match. It is useful when you…

PHP mail() Function: A Complete Guide

PHP mail() is a great built-in function for sending an email directly from your script for account confirmations, password resets, or sending notifications.…

MongoDB CRUD with PHP: Create, Read, Update, and Delete

PHP gives us the ability to work with MongoDB, highlighting the importance of CRUD (Create, Read, Update, Delete) operations for…

Concatenating Strings in PHP: Tips and Examples

In PHP, string operators, such as the concatenation operator (.) and its assignment variant (.=), are employed for manipulating and…

PHP error_log Function: How It Works with Examples

Sometimes things go wrong when PHP runs the code. So, you need to know the reasons for this error to…

IF-Else: Executes the IF-Else Statement in PHP

Programming is all about choices. Everything you do in code boils down to answering a question: What should happen if…

PHP foreach Loop: How to Access Keys & Values in Arrays

PHP foreach loop came to help work with array data in a simple way. Arrays and objects grew more common…

PHP strpos Function: How it Works with Examples

Sometimes the string you expect is there, but strpos function gives a surprise in PHP. It may show the result…

PHP array_column: How to Extract Values from Arrays

The array_column function in PHP takes values from one column in a multidimensional array. You can use it to pull…

Get Last Insert ID in PHP with MySQL PDO and MySQLi

Keeping track of the last record inserted is often important. Whether you are managing user registrations, processing orders, or handling…

Previous Article

History of PHP: From PHP/FI to Modern Web Development

Next Article

PHP Spread Operator: Understand How (…) Syntax Works

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.