note 99748 added to function.array-walk
| From: | matthew at codenaked dot org | Date: | Thu, 02 Sep 2010 18:24:53 +0000 |
| Subject: | note 99748 added to function.array-walk | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-172283@lists.php.net to get a copy of this message | ||
Using lambdas you can create a handy zip function to zip together the keys and values of an array. I
extended it to allow you to pass in the "glue" string as the optional userdata parameter.
The following example is used to zip an array of email headers:
<?php
/**
* Zip together the keys and values of an array using the provided glue
*
* The values of the array are replaced with the new computed value
*
* @param array $data
* @param string $glue
*/
function zip(&$data, $glue=': ')
{
if(!is_array($data)) {
throw new InvalidArgumentException('First parameter must be an array');
}
array_walk($data, function(&$value, $key, $joinUsing) {
$value = $key . $joinUsing . $value;
}, $glue);
}
$myName = 'Matthew Purdon';
$myEmail = 'matthew@example.com';
$from = "$myName <$myEmail>";
$headers['From'] = $from;
$headers['Reply-To'] = $from;
$headers['Return-path'] = "<$myEmail>";
$headers['X-Mailer'] = "PHP" . phpversion() . "";
$headers['Content-Type'] = 'text/plain; charset="UTF-8"';
zip($headers);
$headers = implode("\n", $headers);
$headers .= "\n";
echo $headers;
/*
From: Matthew Purdon <matthew@example.com>
Reply-To: Matthew Purdon <matthew@example.com>
Return-path: <matthew@example.com>
X-Mailer: PHP5.3.2
Content-Type: text/plain; charset="UTF-8"
*/
----
Server IP: 216.235.13.26
Probable Submitter: 173.32.220.24
----
Manual Page -- http://www.php.net/manual/en/function.array-walk.php
Edit -- https://master.php.net/note/edit/99748
Del: integrated -- https://master.php.net/note/delete/99748/integrated
Del: useless -- https://master.php.net/note/delete/99748/useless
Del: bad code -- https://master.php.net/note/delete/99748/bad+code
Del: spam -- https://master.php.net/note/delete/99748/spam
Del: non-english -- https://master.php.net/note/delete/99748/non-english
Del: in docs -- https://master.php.net/note/delete/99748/in+docs
Del: other reasons-- https://master.php.net/note/delete/99748
Reject -- https://master.php.net/note/reject/99748
Search -- https://master.php.net/manage/user-notes.php