PHP foreach loop =>
This question already has an answer here:
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;
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: %sn", $b, $_REQUEST[$a]);
^ ^ ^
| | +--- second variable parameter
| | |
| +---- first variable parameter |
| | |
| V V
+----------- string format "%20s: %sn"
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)
上一篇: 什么= =在PHP中的意思?
下一篇: PHP foreach loop =>