Created
December 28, 2018 18:16
-
-
Save MECU/d81d22172ff4813d6697a970b9db7412 to your computer and use it in GitHub Desktop.
PHP implode improvement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Propose: | |
// Add a "$wrap" or "$prefix" and "$suffix" parameters to the implode() function. | |
// https://secure.php.net/manual/en/function.implode.php | |
// So something like this: | |
$array = ['a', 'b', 'c']; | |
$output1 = '"' . implode(',', $array) . '"'; | |
// Could be changed to something like: | |
$output2 = implode(',', $array, '"'); | |
// And produce identical results: | |
echo $output1; // = "a,b,c" | |
echo $output2; // = "a,b,c" | |
// Thus, the third parameter for implode() would be a string used to "$wrap" both $prefix and $suffix around the resulting implode string. | |
// Further, providing a fouth parameter makes the third parameter only the $prefix, and the fourth parameter would be $suffix. | |
// This would then change this: | |
$output3 = '<ul><li>' . implode('</li><li>', $array) . '</li></ul>'; | |
// To: | |
$output4 = implode('</li><li>', $array, '<ul><li>', '</li></ul>'); | |
// And produce identical results: | |
echo $output3; // = <ul><li>a</li><li>b</li><li>c</li></ul> | |
echo $output4; // = <ul><li>a</li><li>b</li><li>c</li></ul> | |
// So the implode() would then be defined something like: | |
string implode ( string $glue , array $pieces, string $wrap_or_prefix = '', string $suffix = '' ) | |
// Where $wrap will used for $suffix if $suffix is the empty string '' | |
// If $suffix is null, then $wrap will only be used as $prefix. Thus: | |
$output5 = implode('</li><li>', $array, '<ul><li>', null); | |
// Produces: | |
echo $output5; // = <ul><li>a</li><li>b</li><li>c | |
// If $prefix is null, then $suffix will only be used. Thus: | |
$output6 = implode('</li><li>', $array, null, '</li></ul>'); | |
// Produces: | |
echo $output6; // = a</li><li>b</li><li>c</li></ul> | |
// If $prefix and $suffix are null, then both $prefix and $suffix are ignored, and E_NOTICE is raised | |
$output7 = implode('</li><li>', $array, null, null); | |
// Produces: | |
echo $output7; // E_NOTICE; = a</li><li>b</li><li>c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment