Using PHP compact() to Create an Array of Variable Names and Their Values
This article explains how PHP's compact() function builds an associative array by extracting variable names from the current scope, details its parameters and return value, and provides a complete example with code and output illustrating its usage.
The article explains PHP's compact() function, which builds an associative array by mapping variable names to their values from the current symbol table.
It describes that compact() accepts a variable number of arguments, each being a string or an array of strings, and skips any names that do not correspond to defined variables.
The function returns the constructed array containing all matched variables.
Parameter details for varname are provided, and the return value is an array of the added variables.
Example code demonstrates defining variables, creating an array of variable names, calling compact() , and printing the result.
<?php $city = "San Francisco"; $state = "CA"; $event = "SIGGRAPH"; $location_vars = array("city", "state"); $result = compact("event", "nothing_here", $location_vars); print_r($result); ?>
The output of the example is shown below.
Array ( [event] => SIGGRAPH [city] => San Francisco [state] => CA )
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.