The basic syntax of the compact() function is as follows:
<span><span><span class="hljs-title function_ invoke__">compact</span></span><span>(...</span><span><span class="hljs-variable">$var_names</span></span><span>)
</span></span>
The parameter $var_names is one or more strings representing the variable names to be converted into an array. The return value is an associative array containing the variable names and their corresponding values. If a variable is undefined or has a value of null, compact() will still include that variable in the returned array.
For example:
<span><span><span class="hljs-variable">$name</span></span><span> = </span><span><span class="hljs-string">"John"</span></span><span>;
</span><span><span class="hljs-variable">$age</span></span><span> = </span><span><span class="hljs-number">25</span></span><span>;
</span><span><span class="hljs-variable">$city</span></span><span> = </span><span><span class="hljs-string">"New York"</span></span><span>;
<p></span>$result = compact("name", "age", "city");<br>
print_r($result);<br>
</span>
Output:
<span><span><span class="hljs-title function_ invoke__">Array</span></span><span>
(
[name] => John
[age] => </span><span><span class="hljs-number">25</span></span><span>
[city] => New York
)
</span></span>
In this example, the compact() function successfully packs three variables into an array.
PHP’s compact() function includes variables with a value of null in the returned array, with the corresponding value being null.
For example:
...In some cases, we may not want null or empty values in the returned array. To handle this, we can use the array_filter() function on the result of compact(). array_filter() removes empty values (including null, empty strings "", etc.) from the array.
...If you want more precise control over the filtering (e.g., also excluding empty strings or zeros), you can pass a custom callback function to array_filter().
...If you pass undefined variables to compact(), they will be automatically ignored and won’t appear in the returned array. However, if a variable exists but its value is null, it will still appear in the result.
...compact() is a very useful PHP function that converts variables into an associative array. When handling null values, compact() includes them in the array with their value set to null. If you don’t want null or empty values in the array, you can filter the result using array_filter(), or even define custom filtering rules for more fine-grained control.
With these techniques, we can handle variables more flexibly when using compact(), ensuring the returned array meets our needs.
Related Tags:
null