Creating Variables from Array Keys in PHP

If you want to convert associative arrays in variables automatically, you can use the following script. It requires an array from which to extract the variables, and an array of variable names that you want to extract.

Here is the script:

<?php
function array_to_variables( $array = null , $variable_list = array() )
{
 if( $array === null )
 {
  $array = $_GET;
 }
 
 if( !is_array( $variable_list ) )
 {
  $variable_list = explode( ',' , $variable_list );
 }
 
 if( !count( $variable_list ) )
 {
  $variable_list = array_keys( $array );
 }
 
 foreach( $variable_list as $variable_name )
 {
  $variable_name = trim( $variable_name );
  if( preg_match( "/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/" , $variable_name ) )
  {
   GLOBAL $$variable_name;
   if( isset( $array[$variable_name] ) )
   {
    $$variable_name = $array[$variable_name];
   }
   else
   {
    $$variable_name = null;
   }
  }
 }
}?>

And here is how to use it;

<?php
//Example 1
array_to_variables( $_GET , array( 'image_id' , 'session_id' ) );
//Example 2
array_to_variables(  );
?>

In the example 1, it will try to create variables $image_id and $session_id and look for the value in the $_GET array. If the array keys in $_GET array exist with the name 'image_id' and 'session_id', same variables are created successfully. In case of failure it creates variables and saves NULL in those variables.

I second Example, the default array $_GET is taken and it tried to create a variable for every valid associative key. Valid here means an associative key that can be used as variable name.

Hope this is helpful function for you all. Sorry for poor documentation.