How to Use the PHP Function Compact to Create Arrays of Variables
PHP has a built-in function that lets you create an array of variables by joining their names and values. This array compact function allows you to simplify your code, improve readability and reduce error rates.
The compact function accepts variable names as its parameters and outputs an associative array with the variable name serving as the key and the current value of that variable in the present scope as the value for that key. This function is especially useful when you need to pass many variables with the same value to a function, but want to avoid multiple for each loops.
This PHP function can also be used in conjunction with slots, a feature that allows you to assign unique values to each variable in an associative array. This way, you can use the same value in multiple places on your site without having to concatenate them all by hand.
In the past, the compact function was fairly forgiving; on string values that could not be resolved to a variable syntax, it would skip them without further warnings. Beginning with PHP 8.1, this behavior has been changed to emit a warning if a non-string or non-array value is passed to the compact function.
This new behavior makes it easier for you to identify where your code is using illegal types and fix them before they cause bugs or errors on production sites. For example, if you are concatenating all your data variable values in for each loops on every page, it will be hard to find where this is occurring and then change it to something more appropriate, like an array.