Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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); 
like image 671
naththedeveloper Avatar asked May 01 '13 14:05

naththedeveloper


People also ask

What does compact do in PHP?

PHP | compact() Function 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 is the use of compact () function?

Definition and Usage The compact() function creates an array from variables and their values. Note: Any strings that does not match variable names will be skipped.

What does compact () do in laravel?

The compact() function is used to convert given variable to to array in which the key of the array will be the name of the variable and the value of the array will be the value of the variable.

What is a string variable in PHP?

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type. Note: On 32-bit builds, a string can be as large as up to 2GB (2147483647 bytes maximum)


2 Answers

As far as benefits, I've found compact() to be useful in MVC applications. If you're writing controller code and you need to pass an associative array of variables and their apparent names that you've set in your controller to the view, it shortens something like:

View::make('home')->with(array('products' => $products, 'title' => $title, 'filter' => $filter')); 

to

View::make('home')->with(compact('products', 'title', 'filter')); 
like image 175
Andrew Avatar answered Oct 14 '22 17:10

Andrew


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.

like image 38
cdhowie Avatar answered Oct 14 '22 17:10

cdhowie