o9w3kw
Last Updated: February 25, 2016
·
1.201K
· anthonylevings
Speechrocket4 square

Two ways to convert an array of any length into a string with "and" before final entry in PHP

<?php

function author_array($value) {

if (is_string($value)) $author=$value;

else if (is_array($value))
{
$i=0;
$array_length=count($value);
while ($i<$array_length) {

// Final author
if ($array_length-$i==1) $author=$author.$value[$i];
// Penultimate author
else if ($i==$array_length-2) $author=$author.$value[$i]." and ";
// All other entries
else $author=$author.$value[$i].", ";
$i++;
}

}
return $author;
}
echo author_array(array("Sam","Jim", "Jackie","Simon"));
?>

The alternative is to implode the array, and then use regular expressions and string search and replace functions (preg_replace and substr_replace)

<?php

// create an array
$array = array("Sam","Jim", "Jackie","Simon");
// implode the array so we have a string of names with commas inside
$comma_separated = implode(",", $array);

// make commas the search pattern
$pattern = '/(,)/';
// make the replacement the found comma followed by a space
$replacement = '$1 ';
// use the pattern, replacement and string to place spaces inside string after commas
$comma_separated = preg_replace($pattern, $replacement, $comma_separated);

// Create a function for replacing instance of something in a string with something else or in this case borrow it from StackOverflow http://stackoverflow.com/questions/3835636/php-replace-last-occurence-of-a-string-in-a-string

function str_lreplace($search, $replace, $subject)
{
    $pos = strrpos($subject, $search);

    if($pos !== false) $subject = substr_replace($subject, $replace, $pos, strlen($search));

    return $subject;
}

// replace final comma with "and"
echo str_lreplace(","," and ",$comma_separated);

?>
Say Thanks
Respond