What I'd like to do is have a function to get numerous variable names from an array and then pass them through a function which will define the variables. That is, I'd like to turn:

$lg_id = $_POST['lg_id'];
$lg_initials = $_POST['lg_initials'];
...

into a loop.

What I've got so far is:

	// to get variable names which basically looks like:
	// $sfn[0] = '';
	// $sfn[1] = 'lg_id';
	// $sfn[2] = 'lg_initials';
	// ...
	include("includes/arrays.inc");

// lose these as they're not in $_post
unset($sfn[0],$sfn[1],$sfn[30]);
// lose submit from $_POST
array_pop($_POST);

// get rid of http:// in URL
$_POST['site_address'] = ereg_replace("^http://", "", $_POST['site_address']);

// define multiple vars
// got the basis of this function from http://ca3.php.net/variables.external
function get_superglobal_vars_from_POST() {
   $numargs = func_num_args();
   $setargs = 0; // for counting set variables
   for ($i=0; $i<$numargs; $i++) {
	   $varname=func_get_arg($i);
	   if (!isset($_POST[$varname])) {
		   $result='';
	   } else {
		   $result=$_POST[$varname];
		   $setargs++;
	   }   
	   $GLOBALS[$varname]=$result;
   }
   //return $setargs; // who cares?
}

// put quotes around variable names
$headerswithquotes = "'" . implode ("','", $sfn) . "'";

// pass variable names as args to function
get_superglobal_vars_from_POST($headerswithquotes);

// check that they're defined and in correct order
echo '<pre>';
print_r($_POST);
echo '</pre>';

but that doesn't work. 🙁

What does seem to work is replacing:

	get_superglobal_vars_from_POST($headerswithquotes);

with:

	get_superglobal_vars_from_POST('lg_id','lg_initials'...);

but that defeats the purpose of getting the numerous var names from the array.

and when I:

	print_r($headerswithquotes);

it spits out what I want in:

'lg_id','lg_initials'...

so why doesn't it work? I guess maybe b/c the function call doesn't like a var as args. But more importantly, how do I get what I want?

As an aside, I read about "return" in the php manual, but I still don't get why that person included it in the function. I commented it out because the author commented "who cares?", but could someone explain what it's supposed to do?

As always, thanks in advance!

    if all you want to do is create variables from the elements of an array then use the [man]extract[/man] function.

      Thanks for the super fast replies, guys! I'll read through your links right away.

        extract($_POST);

        seems to do part of what I want. If a var is set then it defines it, but when it is not set then it doesn't. That is, it misses out on the:

        		   if (!isset($_POST[$varname])) {
        			   $result='';
        		   }
        

        part from above.

        As a result, when later on in my code I have:

        	$headers = implode (",", $sfn);
        	$inputs = "'" . implode ("','", $_POST) . "'";
        
        // just to check that they're all there which they're not with extract()
        	echo '<pre>';
        	print_r($headers.'<P>'.$inputs);
        	echo '</pre>';
        
        $query = "INSERT INTO leagues ($headers) VALUES ($inputs)";
        

        There's 31 headers displayed but only 21 inputs. It's missing the 10 radio option inputs (say the inputter did not want to select anything for them) that were to be defined as ='' and without them it fails to insert.

        extract($_POST);

        is great as it's much simpler than what I was trying to do, but is there some way I can use it and define the variables that are not set?

        Or maybe my only option is to get the function in my first post to work?

          if i undertsand you correctly, you have an array that contains all of the fields that you are expecting via POST as well as some that may not be set at all (like uncheccked checkboxes and radios). you want to create variables for all of the POST vars that exist as well as all the others that don't (just using a blank string). if so then you could :

          foreach ($array as $value)
          {
          	if (isset($_POST[$value])) {$$value = $_POST[$value];}
          	else {$$value = '';}
          }
          

          $array is the array containing all of the field names.

            Oh, we're so close now I can smell it! 🙂

            Your:

            	foreach ($sfn as $value) {
            		if (isset($_POST[$value])) {
            			$$value = $_POST[$value];
            		} else {
            			$$value = '';
            		}
            	}  

            with the help of:

            	echo '<pre>';
            	print_r($_POST);
            	echo '</pre>';
            
            $headers = implode (",", $sfn);
            $inputs = "'" . implode ("','", $_POST) . "'";
            
            echo '<pre>';
            print_r($headers.'<P>'.$inputs);
            echo '</pre>';
            

            spit out:

            Array
            (
                [lg_initials] => kjghg
                [lg_full_name] => gchgchg
                [site_address] => 
                [email_address] => 
                [commissioner_real_name] => 
                [commissioner_nick_name] => 
                [participants] => Solo
                [membership_fee] => 
                [export_deadlines] => 
                [sim_period] => 
                [teams] => 
                [ratings_scales] => 
                [evaluation_weights] => 
                [era] => 
                [modifiers] => 
                [payroll_cap] => 
                [first_season] => 
                [current_season] => 
                [date_established] => 
                [third_party] => 
                [additional_info] => 
                [password] => 
            )
            
            lg_initials,lg_full_name,defunct,site_address,email_address,commissioner_real_name,commissioner_nick_name,participants,role_played,openings,game_version,game_needed,membership_fee,export_deadlines,sim_period,players,teams,development,coaches_scouts,ratings_scales,evaluation_weights,era,modifiers,financials,payroll_cap,first_season,current_season,date_established,third_party,additional_info,password
            
            'kjghg','gchgchg','','','','','Solo','','','','','','','','','','','','','','',''
            

            (defunct and participants are two of those radio options.)

            So that didn't quite work as still many of the inputs, including defunct, are still missing from the $_POST array.

            But rearranging your code to:

            	foreach ($sfn as $value) {
            		if (!isset($_POST[$value])) {
            			$_POST[$value] = 'NULL';
            		}
            		$$value = $_POST[$value];
            	}  

            (I believe 'NULL' is as good as '' for my purposes, but easier to pick out for now.)

            spits out:

            Array
            (
                [lg_initials] => kjghg
                [lg_full_name] => gchgchg
                [site_address] => 
                [email_address] => 
                [commissioner_real_name] => 
                [commissioner_nick_name] => 
                [participants] => Solo
                [membership_fee] => 
                [export_deadlines] => 
                [sim_period] => 
                [teams] => 
                [ratings_scales] => 
                [evaluation_weights] => 
                [era] => 
                [modifiers] => 
                [payroll_cap] => 
                [first_season] => 
                [current_season] => 
                [date_established] => 
                [third_party] => 
                [additional_info] => 
                [password] => 
                [defunct] => NULL
                [role_played] => NULL
                [openings] => NULL
                [game_version] => NULL
                [game_needed] => NULL
                [players] => NULL
                [development] => NULL
                [coaches_scouts] => NULL
                [financials] => NULL
            )
            
            lg_initials,lg_full_name,defunct,site_address,email_address,commissioner_real_name,commissioner_nick_name,participants,role_played,openings,game_version,game_needed,membership_fee,export_deadlines,sim_period,players,teams,development,coaches_scouts,ratings_scales,evaluation_weights,era,modifiers,financials,payroll_cap,first_season,current_season,date_established,third_party,additional_info,password
            
            'kjghg','gchgchg','','','','','Solo','','','','','','','','','','','','','','','','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL'
            

            which is oh so close to what we want, except for one problem. See how in the bottom line 'Solo' is the seventh input? Well, if you look at the second to last line, it's actually supposed to be the eighth, as 'participants' (the key for the value Solo) is the eighth header. So what's happening is it's trying to insert the value 'Solo' into the 'commissioner_nick_name' column when it's supposed to be in the 'participants' column. The reason why is because no option for defunct was selected so the defunct key got a null value, but it was pushed to the bottom of the $_POST array, which caused everything after it, including participants, to be pushed up one slot.

            How can I make it so that it will retain the order it should have? That is, how can I get:

            'kjghg','gchgchg','','','','','Solo','','','','','','','','','','','','','','','','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL'

            to become:

            'kjghg','gchgchg','NULL','','','','','Solo'...

            ? Notice how the NULL value for the defunct key was pushed up to the 3rd slot and 'Solo' was pushed to the 8th along with other slot arrangements past that? I could rearrange the form inputs, but I'd really rather not as there's a logical order to them for the user.

              I ended up adding pre-selected N/A radio options that force a value to be passed to the $POST array. After searching more for a solution it sounded like my latest problem was that when no radio button is selected it doesn't add an element for that option to $POST. So, you have to make sure it does by either adding an already selected radio option, or adding after with !isset. But with the latter it only adds it to the end of the array because it's after the array has been first formed. I imagine there's probably another way of inserting it somewhere in the middle of the array afterwards, but it's probably more complicated and it's also probably best for the user to have those default N/A options.

              I can then use:

              extract($_POST);  

              or:

              	foreach ($sfn as $value) {
              		$$value = $_POST[$value];
              	}  

              just fine.

              Anyway, thanks guys! I had been going in circles over the original problem. 🙂

                Write a Reply...