Jump to content


Photo

Form script by David Powers


  • Please log in to reply
1 reply to this topic

#1 php_discipulus

php_discipulus

    Newbie

  • Members
  • Pip
  • 3 posts

Posted 14 May 2013 - 05:42 PM

On page 111 from the book PHP Solutions Dynamic Web design made easy Second Edition. There was a code that made sure the fields aren't blank can somebody explain this code to me please I am having a hard time understanding it

foreach($_POST as $key => $value) {
	// assign to temporary variable and strip whitespace if not an array
	$temp = is_array($value) ? $value : trim($value);
	// if empty and required, add to $missing array
	if (empty($temp) && in_array($key, $required)) {
		$missing[] = $key;
	} elseif (in_array($key, $expected)) {
		// otherwise, assign to a variable of the same name as $key
		${$key} = $temp;
	}
}

and here is the rest of the code for the form:

<?php  

$missing = array();

if (isset($_POST['send'])) {

	$to = 'myemail@example.com';
	$subject = 'Form subject';

	$expected = array('name', 'email', 'comment');
	$required = array('name', 'email', 'comment');

}

?>

<form method="post" action="">
	<p>
		<label for="name">Enter your name:</label><br>
		<input type="text" name="name" id="name" />
	</p>
	<p>
		<label for="email">Enter your email:</label><br>
		<input type="text" name="email" id="email" />

	</p>
	<p>
		<label for="email">Enter comment:</label><br>
		<textarea name="comment" id="comment" cols="40" rows="10"></textarea>
	</p>
	<p>
		<input type="submit" name="send" id="send" value="Send" />
	</p>
</form>

Edited by php_discipulus, 14 May 2013 - 05:43 PM.


#2 mac_gyver

mac_gyver

    Advanced Member

  • Administrators
  • 2,567 posts

Posted 15 May 2013 - 12:03 AM

what exactly don't you understand about the code that the comments don't explain?


multi-purpose programming fool. well written source-code should be self-documenting. well written code should be self-troubleshooting. 





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com