EscoMaji
EscoMaji

Reputation: 763

php variables to array - opposite of "extract"

PHP has a function extract that will convert an array like this:

$array = array(
 'var1' => 1,
 'var2' => 2
);

to:

$var1 = 1;
$var2 = 2;

now, I need the opposite, i have few variables:

$var3 = 'test';
$test = 'another';
$datax = 1;

that needs to be:

$array = array(
 'var3' => 'test',
 'test' => 'another',
 'datax' => 1
);

Is there something like this in PHP?

Upvotes: 10

Views: 5688

Answers (4)

Marcin Szulc
Marcin Szulc

Reputation: 1251

You can use compact() to achieve this.

$var3 = 'test';
$test = 'another';
$datax = 1;
$array = compact('var3', 'test', 'datax');

Reference: http://php.net/manual/en/function.compact.php

Upvotes: 24

silly
silly

Reputation: 7887

like this

$preDefined = (get_defined_vars());
$var3 = 'test';
$test = 'another';
$datax = "1";
$newDefined = array_diff(get_defined_vars(), $preDefined);
print_r($newDefined);

Upvotes: 4

Joe
Joe

Reputation: 15802

You'd have to be really sure you wanted to do this (it includes things in the global scope automatically) but you can use

$my_vars = get_defined_vars();

If you want it more selective than that, you could look at filtering it like this:

$my_vars = pack_vars(get_defined_vars())

function pack_vars ($defined_vars)
{
    $packed = array();
    $ignored = array('dont_use_this', 'ignored_var', 'ignore_this_too');

    foreach ($defined_vars AS $key => $value)
    {
        if (!in_array($key, $ignored))
        {
            $packed[$key] = $value;
        }
    }
    return $packed;
}

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 131811

$array = get_defined_vars()

See get_defined_vars()

Upvotes: 2

Related Questions