Compact and Extract

Compact takes individual variables, and packs them into an associative array. Extract does the opposite.

<?php
// example code

// Set 2 variables
$var1 = "one";
$var2 = "two";

// Create associative array
$arr = compact('var1','var2');

// Show results
var_dump($arr);

/* Output
array(2) {
  ["var1"]=>
  string(3) "one"
  ["var2"]=>
  string(3) "two"
}
*/


// Clear out the originals
unset($var1);
unset($var2);

// Recreate the variables from the array
extract($arr);

// Output the variables to prove they're back
var_dump($var1,$var2);

/* Output
string(3) "one"
string(3) "two"
*/

 

Leave a Reply

Your email address will not be published. Required fields are marked *