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:
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:
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.