Page 1 of 1

Need help building an associative array

Posted: Thu Jul 22, 2010 7:37 am
by Skiddles2010
Can anyone tell me why the following code print_r's to something like:
Array ( [0] => 'MAX_FILE_SIZE'=>'1000000', 'actual_type'=>'Map', 'obj_name'=>'teagfsagsd', 'map_region'=>'gasdfadsf', 'map_type'=>'Dungeon', 'map_connections'=>'wgrgawg' )
Instead of something like:
Array ('MAX_FILE_SIZE'=>'100000', 'ACTUAL_TYPE'=>'Map', so on and so forth... )
I'm just trying to build a smaller array from the contents that were actually filled out in the post and I'd like to reference them by their original form names.

Code: Select all

<?
	// accept the POST...
	$rawPost = $_POST;
	
	// call the function to create new lightPost...
	cleanPost($rawPost);
	
	function cleanPost($heavyPost)
	{	
		foreach($heavyPost as $key => $value)
		{
			if (!empty($value))	
			{
				$string .= "'" . $key . "'=>'" . $value . "', ";
			}
		}
		
		// remove the trailing space and comma...
		$lightPost = substr_replace($string,"",-2);
	
		// build a new array
		global $post;
		$post = array($lightPost);

		print_r($post);
	
	} // end FUNC
?>

Re: Need help building an associative array

Posted: Thu Jul 22, 2010 7:47 am
by AbraCadaver
What are you trying to do here?

Re: Need help building an associative array

Posted: Thu Jul 22, 2010 9:07 am
by Skiddles2010
I have a fairly dynamic form that prompts the user to provide input for certain fields via showing and hiding divs. Upon hitting submit, ALL the variable are $_POST'd, including the blank form variables in the hidden divs. In the form processing file, I'm trying to build a new associative array based off of the fields that actually took some type of input.

Re: Need help building an associative array

Posted: Thu Jul 22, 2010 10:15 am
by AbraCadaver
Skiddles2010 wrote:I have a fairly dynamic form that prompts the user to provide input for certain fields via showing and hiding divs. Upon hitting submit, ALL the variable are $_POST'd, including the blank form variables in the hidden divs. In the form processing file, I'm trying to build a new associative array based off of the fields that actually took some type of input.
Assuming that valid entries are not 0 or blank, you can just use array_filter. This will remove all blank or 0 values:

Code: Select all

$_POST = array_filter($_POST);
To also remove values that are just spaces you can trim the values as well:

Code: Select all

$_POST = array_filter(array_map('trim', $_POST));

Re: Need help building an associative array

Posted: Thu Jul 22, 2010 10:32 am
by Skiddles2010
Ahh, perfect! Seems like there's a shortcut function for everything I want to do in PHP... haha.