0

So I've been researching into PHP to create a basic email form and I came across some code which I decided I would take a look at and experiment with.

The HTML form I am working with is:

<form method="post" action="newsjoin.php"> 

<table align=center> 
<tr>
  <td><select name="sendto" hidden="hidden"> <option value="newsletter@myDomain.com" selected="selected">Newsletter</option> </select></td>
</tr> 
<tr>
  <td><font color=red>*</font> Name:</td>
  <td><input size=25 name="Name"></td>
</tr> 
<tr>
  <td><font color=red>*</font> Email:</td>
  <td><input size=25 name="Email"></td>
</tr>
<tr>
  <td><input type="radio" name="list" value="No" hidden="hidden" /> <input type="radio" name="list" value="Yes" hidden="hidden" checked="checked" /></td>
</tr>
<tr>
  <td colspan=2 align=left><input type=submit name="send" value="Submit"></td>
</tr> 
<tr>
  <td><br /></td>
</tr>
<tr>
  <td colspan=2 align=left><small>A <font color=red>*</font> indicates a field is required</small></td>
</tr> 
</table> 

</form> 

And my newsjoin.php file contains:

<?php 
$to = $_REQUEST['sendto'] ; 
$from = $_REQUEST['Email'] ; 
$name = $_REQUEST['Name'] ; 
$headers = "From: $from"; 
$subject = "Web Contact Data"; 

$fields = array(); 
$fields{"Name"} = "Name";
$fields{"Email"} = "Email";
$fields{"list"} = "Mailing List";

$body = "We have received the following information:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); } 

$headers2 = "From: newsletter@myDomain.com"; 
$subject2 = "Thank you for contacting us"; 
$autoreply = "Thank you for subscribing to our mailing list. You should recieve another email shortly confirming our reciept of this information.";

if($from == '') {
    print "You have not entered an email, please go back and try again.";
} 
else { 
    if($name == '') {
        print "You have not entered a name, please go back and try again.";
    } 
    else { 
        $send = mail($to, $subject, $body, $headers);       // this is the mail to site staff
        $send2 = mail($from, $subject2, $autoreply, $headers2);     // this is the mail to the user
        if($send) {
            header( "Location: http://www.myDomain.com/newsletter_joined.html" );
        } 
        else {
            print "We encountered an error sending your mail, please notify admin@myDomain.com"; 
        } 
    }
}
?> 

Now, this all looks ok to me except for I don't understand this line:

$body = "We have received the following information:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); } 

Namely, I do not understand the $a => $b section, nor do I understand the use of these variables(if they are variables) in the sprint() function.

I have spent the past 4 hours on Google trying to learn what I can about php being used this way and had no luck.

Thanks!

Pavan
  • 15,460
  • 8
  • 56
  • 99
Mike
  • 23
  • 3
  • Spending those four hours, can you please outline where your problem to understand this circulate? What prevents you from understanding? – hakre Apr 22 '14 at 11:52

1 Answers1

3

That is a key-value-pair enumeration. Basically, it's iterating over the collection $fields and at each iteration, it binds the variable $a to the key, and the variable $b to the value.

  foreach($fields as $a => $b)
  {
      // iterates over all key-value pairs in the collection $fields
      //   at each iteration (for each key-value pair in the collection)
      //   $a is bound to the key
      //   $b is bound to the value
  }

If you had an associative array like this:

  $collection = array(1 => 'one', 2 => 'two', 3 => 'three');

Then the following loop would print: 1: one; 2: two; 3: three;

  foreach($collection as $key => $value)
  {
      echo $key.': '.$value.'; ';
  }

nor do I understand the use of these variables(if they are variables) in the sprint() function.

For the second part of your question, the sprintf function essentially generates a formatted string based on the format pattern, and the variables given. So:

sprintf("%20s: %s\n", $b, $_REQUEST[$a]);
           ^           ^     ^
           |           |     +--- second variable parameter
           |           |                                |
           |           +---- first variable parameter   |
           |                                       |    |
           |                                       V    V
           +----------- string format            "%20s: %s\n"

returns a formatted string that outputs a:

  • right-justified, space padded, fixed width (20 character) string representation of the first parameter (variable $b which as explained above is the value in the key-value enumeration),

  • followed by colon,

  • followed by a space, and then

  • followed by the string representation of the second parameter ($_REQUEST[$a] which is a value from the $_REQUEST array, indexed by the value of the variable $a, which again, as explained above, is bound to the key in the key-value pair enumeration)

Mike Dinescu
  • 48,812
  • 10
  • 104
  • 136
  • Hmm, a comment with a link to the PHP manual would have given perhaps better information in more languages with more user-comments, but well, it's of such fundamental topic, that it's worth to give it a personal touch, why not. Well, not. – hakre Apr 21 '14 at 22:31
  • I actually think the question didn't have as much to do with the loop and => operator as it did with the use of sprintf and looping on a single line to output all the $_REQUEST values. Unfortunately, before people read that and parse it out, the high rep guys come in and chastise the guy and everyone climbs on the bandwagon. Fundamental problem with SO. – Mattt Apr 21 '14 at 22:33
  • @Hakre this is hands down a better answer about the use of sprintf in this situation than the duplicates you offered. You and others voting to close good questions like this before you fully comprehend them is poor at best. – Mattt Apr 21 '14 at 22:41
  • @Matt - thanks for the support. Sometimes, it's easy to forget that novice programmers need a bit of hand holding beyond the use of reference documentation. I know I've been quick to pull the trigger on some questions myself. – Mike Dinescu Apr 21 '14 at 22:42
  • Question clearly shows the lack of effort to at least, identify the problem, claims that one spent 4 hours and haven't found the answer is highly unlikely and is a kind of *fu* to everyone that contributed to PHP manual. Manual is clear enough and if person can't understand it, it's another problem. +1 for @MikyDinescu anyways. – Dejan Marjanović Apr 21 '14 at 22:54
  • @TOOTSKI, you may be right. Perhaps the OP's claim to have spent 4 hours is a bit exaggerated, and I'll grant you that the question is poorly formulated. But this is one of those questions that only a novice programmer would ask because if he knew the right questions to ask he wouldn't need to ask them. I think sometimes it's worth taking the time to explain things and help beginners by clarifying certain topics for them. – Mike Dinescu Apr 21 '14 at 22:59
  • Well, re-reading the question is sounds much like tutoring request for two specific points to review within code. That's not a good question, actually it's grey area if it's a question suitable for Q&A at all. Please do not drop tutoring requests but formulate a programming question. That's the minimal effort normally looking for. – hakre Apr 22 '14 at 11:51