Get user defined variables

Views: 23 Last modified: August 12th, 2011 Comments: 0

You want to see all the user defined variables in PHP ? Well, that’s quite easy. The below PHP function will retrieve all the defined variables, such as globals, POST and GET, but filters them all out and returns only the user defined variables.

The user defined variables will be returned in a array, whereas the array keys will present the variable names and the array values the variable values.

Just see the example below!

<?php
// Var: String
$var_string = 'A string';

// Var: Integer
$var_int = 55;

// Var: Boolean
$var_boolean = (int)false;

/**
 * GetUserDefinedVariables()
 * Return all the user defined variables
 * @param array $variables (Defined variables)
 * @return array $user_variables
 */
function GetUserDefinedVariables($variables){;
    if (!is_array($variables))
        return false;

    $user_variables = array();

    foreach ($variables as $key => $value)
        if (!@preg_match('@(^_|^GLOBALS)@', $key))
            $user_variables[$key] = $value;

        return $user_variables;
}

echo '<pre>'.print_r(
                        GetUserDefinedVariables(
                                        get_defined_vars()
                                                ), true).'</pre>';
?>

The result of the above snippet…

Array
(
    [var_string] => A string
    [var_int] => 55
    [var_boolean] => 0
)
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

    Mail this!

    To: From:Sum {1+8} =  
    Anything to add ?

        You must be logged in to post a comment.