Difference between compact function and literal array assignment


According to the PHP documentation, the function compact .


For each of the passed parameters, compact() looks for a variable with the name specified in the symbol table and adds it to the output array so that the variable name will be the key and its contents will be the value for this variable key.

That is, it can create a array based on the names of the variables of the local scope.

I usually use this function in some cases to be able to transform some of the values I'm using into variables into array .

For example:

function process_request(array $data) {
      $body = $data['response']->getBody();
      $headers = $data['request']->getHeaders();

       // Resto do código

$request = new Request;
$response = new Response;
process_request(compact('response', 'request'));

In the specific case above, it could also be done with literal attribution of a array :

process_request(['response' => $response, 'request' => $request])

I usually use compact instead of direct attribution simply because of aesthetics (vanity with code). But it sometimes comes to my mind that compact is a function, since direct assignment is not, and that may imply performance.

So, I ask:

  • Which of the two forms are most appropriate?

  • All PHP versions support the compact function?

asked by anonymous 09.12.2016 / 20:09

1 answer

  • I do not think you will find any performance gains using any of the available methods over another. This really comes down to readability and what makes the most sense when looking at the code.
  • The function is available from PHP 4, PHP 5, PHP 7.
  • I use compact() in Laravel 5 for the development of a PR system and I have no problem with slowness.
12.12.2016 / 13:17