Skip to content
Advertisement

Why does PHP compact() use strings instead of actual variables?

Can anyone explain the benefit of PHP’s compact() function accepting the string of ‘a variable with that name’ instead of the actual variable?

For example:

$foo = 'foo';
$bar = 'bar';

$compacted = compact('foo', 'bar');

Why do I need to pass a string of the variable name instead of just passing the variable itself and PHP handling mapping this to an array? Like so:

$compacted = compact($foo, $bar);

Advertisement

Answer

Because the compact() function needs to know the names of the variables since it is going to be using them as array keys. If you passed the variables directly then compact() would not know their names, and would not have any value to use for the returned array keys.

However, I suggest building the array manually:

$arr = array(
    'foo' => $foo,
    'bar' => $bar);

I consider compact() deprecated and would avoid using it in any new code.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement