php

What is compact() Function in PHP

In PHP, developers need to join the names of variables with their corresponding values to build an array that frequently occurs. To simplify this procedure and get rid of repetitive code, the “compact()” function can be used. It is helpful when users require obtaining values into an associative array or sending numerous variables to a function.

This tutorial will demonstrate the “compact()” function in PHP.

What is compact() Function in PHP?

In PHP, the “compact()” function is designed to combine the names of variables with their corresponding values to produce an array. It accepts a number of variables with names as parameters and outputs an array with the variable names serving as keys. The current values of the associated variables in the present scope as their values.

Syntax

The “compact()” function’s syntax is provided below:

compact(variable_Name1, variable_Name2, ...)

In the above code, the “compact()” function accepts parameters as “variable_Name1”, “variable_Name2”, and so on, indicating the name of the variables that will be present in the final array, and It returns all the variables that are added to the array.

Example: Display Array With Variable Names as Keys Using “compact()” Function in PHP

To understand the working of the “compact()” method, first, declare three variables “$my_name”, “$my_age”, and “$subject” that are initialized with respective values as “Usama”, “25” and “Computer Science”. Then, invoke the “compact()” function with the required parameter and store it in the “$final_result” variable. After that, apply the “print_r()” function and pass it to the “$final_result” array to get the results:

<?php

$my_name = "Sam";

$my_age = 25;

$subject = "Computer Science";

$final_result = compact('my_name', 'my_age', 'subject');

print_r($final_result);

?>

Output

Note: The “compact()” function is used in PHP to reduce code repetition when working with templates or view files. Instead of manually specifying each variable to be passed to a template, developers can dynamically create an array of variables using the “compact()” function and extract them within the template.

This demonstration provided detailed information about the “compact()” function in PHP.

Conclusion

In PHP, the “compact()” function is a useful technique for associating the names of variables with their corresponding values to produce an associative array. By using this method, programmers may improve the process of sending variable data to methods or templates, minimize redundancy, and streamline their code. In this guide, we have explained the “compact()” functions in PHP.

About the author

Kaynat Asif

My passion to research new technologies has brought me here to write for the LinuxHint. My major focus is to write in C, C++, and other Computer Science related fields. My aim is to share my knowledge with other people.