Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compact() vs manual array declaration on PHP

Tags:

arrays

php

I am usually using compact() function of php for the building array from the variables. Also, I can create that array manually. Are there any pros or cons of those usages? I am sharing an examples both of those declarations on the following segment:

Compact Usage

   <?php 
    $name = "John";
    $surname = "Doe";
    compact('name','surname');
?>

Output:

['name'=>'John','surname'=>'Doe']

Manual Array Declaration

<?php 
$name = "John";
$surname = "Doe";
$data = array("name"=>$name,"surname"=>$surname);
?>

Output:

['name'=>'John','surname'=>'Doe']
like image 369
bl4cksta Avatar asked Feb 23 '16 21:02

bl4cksta


People also ask

What is the use of compact function in PHP?

The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values.

What are the two types of PHP arrays and how do they differ?

Create an Array in PHP In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

What is compact array?

compact() is a Ruby method that removes all nil values from an array and returns the array without any nil values. This method does not change or modify the original array. It only returns a copy of the array without nil values.

What is difference between compact and with in laravel?

with() is a Laravel function and compact() is a PHP function and have totally different purposes. with() allows you to pass variables to a view and compact() creates an array from existing variables given as string arguments to it.


2 Answers

2021 Static Analysis Answer

The compact() used to be a handy shortcut for printing array of variables. Yet nowadays, when we have PHPStan, Rector, IDE and strict types in PHP, using compact brings a huge obstacle for static analysis and IDE autocomplete.

Using explicit variables (2.) empowers your IDE and other tool to know the types and helps you with code autocompletion, static analysis and automated refactoring.


1. Using compact()

function getValues(...) {
    $name = 'Elon';
    $surname = 'Musk';
    return compact('name','surname');
}

$items = getValues();

How does IDE/PHPStan/Rector see it?

  • it's a function
  • there are 2 strings
  • return type of getValues() is mixed[]
  • there are 2 unused variables - $name and $surname
foreach ($items as $item)
{
    $item->? // it's mixed
}

2. Using Explicit variables

function getValues(...) {
    $name = 'Elon';
    $surname = 'Musk';

    return [
        'name' => $name,
        'surname' => $surname,
    ]);
}

$items = getValues();

How does IDE/PHPStan/Rector see it?

  • it's an array
  • there are 2 items
  • return type of getValues() is array<string, string>
foreach ($items as $item)
{
    $item->? // it's a string
}

Compare PHPStan results Yourself

  • explicit: https://phpstan.org/r/48f4ce8b-c964-4a06-b03f-c182fb2d487f
  • compact: https://phpstan.org/r/8023498a-b4fc-40e0-9086-36adafa1b2e3

enter image description here

like image 51
Tomas Votruba Avatar answered Oct 08 '22 10:10

Tomas Votruba


I think it's more a matter of preference.

Uses

If I have a bunch of local variables declared, and I happen to want my array keys to be named the same way, compact is very helpful.

I don't find that to be the case very often though. Typically I'm defining an array that is more complex:

$array = [
    'foo' => $something->foo(),
    'bar' => $bar,
    'baz' => A_CONSTANT
];

To use compact here you'd have to define your variables $foo $bar and $baz first, which seems silly.

I like compact, I just don't find it to be all around helpful most of the time.

Performance

Ok I had to go do it. Here's a very basic non-scientific performance comparison:

https://3v4l.org/WTrOJ

In short, using compact is an order of magnitude slower.

And yet, you have to use it 100,000 (in this example) to matter a tiny fraction of a second.

In other words: use what makes the most sense for your code. Don't worry about the incredibly small performance difference!

like image 41
jszobody Avatar answered Oct 08 '22 11:10

jszobody