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:
<?php $name = "John"; $surname = "Doe"; compact('name','surname'); ?>
Manual Array Declaration
<?php $name = "John"; $surname = "Doe"; $data = array("name"=>$name,"surname"=>$surname); ?>
I think it’s more a matter of preference.
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 ];
compact here you’d have to define your variables
$baz first, which seems silly.
compact, I just don’t find it to be all around helpful most of the time.
Ok I had to go do it. Here’s a very basic non-scientific performance comparison:
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!