note 76295 deleted from function.implode by hholzgra
| From: | hholzgra@php.net | Date: | Thu, 02 Aug 2012 13:18:58 +0000 |
| Subject: | note 76295 deleted from function.implode by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189744@lists.php.net to get a copy of this message | ||
Note Submitter: thomas at tgohome dot com
----
This is my quick function to create a list, English style, but will accept any glue, so you could
use 'or', or even 'or though, it could be', etcetera. It should also support PHP
4, although I haven't tested it; it doesn't use the PHP 5 negative substr() trick.
<?php
/**
* Quick script to join items in an array, English
* style; using the "one, two and three" style.
*
* Copyright 2007 Thomas O. Feel free to redistribute
* so long as this copyright remains.
*/
function implode_ea($glue_punct, $glue_word, $array) {
// Implode the entire array
$result = implode($glue_punct, $array);
// Check the length of the array
if(count($array) > 1) {
// Calculate the amount needed to trim
$trimamount = strlen($array[count($array) - 1]) + strlen($glue_punct);
// Trim the imploded string
$result = substr($result, 0, strlen($result) - $trimamount); // PHP 4 compatible
$result = "$result $glue_word " . $array[count($array) - 1];
// Return the result
return $result;
} else {
// In this case, the array cannot be splitted by a
// word or punctuation, because it is too small.
return $result;
}
}
echo implode_ea(", ", "and", array("one", "two",
"three"));
?>
(implode_ea stands for 'Implode, English And style')
Hope this helps,
Tom