search for in the  
<asortcount>
Last updated: Thu, 19 May 2005

compact

(PHP 4, PHP 5)

compact --  Create array containing variables and their values

Description

array compact ( mixed varname [, mixed ...] )

compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.

For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract(). It returns the output array with all the variables added to it.

Any strings that are not set will simply be skipped.

Gotcha: Because variable variables may not be used with PHP's Superglobal arrays within functions, the Superglobal arrays may not be passed into compact().

Example 1. compact() example

<?php
$city 
= "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "nothing_here", $location_vars);
?>

After this, $result will be:

Array
(
   [event] => SIGGRAPH
   [city] => San Francisco
   [state] => CA
)

See also extract().



User Contributed Notes
compact
pillepop2003 at yahoo dot de
22-Nov-2004 02:26
Use the following piece of code if you want to insert a value into an array at a path that is extracted from a string.

Example:
You have a syntax like 'a|b|c|d' which represents the array structure, and you want to insert a value X into the array at the position $array['a']['b']['c']['d'] = X.

<?
  
function array_path_insert(&$array, $path, $value)
   {
      
$path_el = split('\|', $path);
      
      
$arr_ref =& $array;
      
       for(
$i = 0; $i < sizeof($path_el); $i++)
       {
          
$arr_ref =& $arr_ref[$path_el[$i]];
       }
      
      
$arr_ref = $value;
   }

  
$array['a']['b']['f'] = 4;
  
$path  = 'a|b|d|e';
  
$value = 'hallo';
  
  
array_path_insert($array, $path, $value);

  
/* var_dump($array) returns:

   array(1) {
     ["a"]=>
     &array(1) {
       ["b"]=>
       &array(2) {
         ["f"]=>
         int(4)
         ["d"]=>
         &array(1) {
           ["e"]=>
           string(5) "hallo"
         }
       }
     }
   */

?>

Rock on
Philipp
rlynch at ignitionstate dot com
27-Jan-2000 02:43
It should be noted that PHP will simply skip any strings that are not set:

<?php
  $foo
= 4;
 
$bar = 3;
 
$result = compact('foo', 'bar', 'baz');
?>

will result in:
('foo' => 4, 'bar' => 3)
'baz' is simply ignored.

<asortcount>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT