Skip to content

Instantly share code, notes, and snippets.

@mikey179
Last active December 17, 2015 00:19
Show Gist options
  • Save mikey179/5520225 to your computer and use it in GitHub Desktop.
Save mikey179/5520225 to your computer and use it in GitHub Desktop.
Which one is better? Both functions do the same, but in slightly different ways. Interestingly, the second one takes around 4 times longer than the first one.
function convertToStringRepresentation1($value)
{
$string = '';
$lines = explode("\n", (string) $value);
foreach ($lines as $lineCounter => $line) {
if (empty($line)) {
continue;
}
if (0 != $lineCounter) {
$string .= ' ' . $line . "\n";
} else {
$string .= $line . "\n";
}
}
return $string;
}
function convertToStringRepresentation2($value)
{
return join("\n ",
array_filter(explode("\n", (string) $value),
function($line)
{
return !empty($line);
}
)
) . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment