1

I want to create a function that returns string from array with comma. Before last items will have and not comma. As like I have this code...

$arr= array('arif', 'tanvir', 'sujon')

In case of one items arif or anything without comma.In case of two items, arif and tanvir or anything . In case of three items arif, sujan and tanvir.

1 Answer 1

1

You need to use the php implode function:

$arr= array('arif', 'tanvir', 'sujon')
$comma_separated = implode(",", $arr);
echo $comma_separated;

EDIT: now I understood the requirement of the asker. You need to iterate over the array and check de index of the element:

$arr= array('arif', 'tanvir', 'sujon');
$array_size = count($arr);
$result = $arr[0];
for ($i = 1; $i < $array_size; $i++) {
    if ($i < $array_size-1)
        $result .= ", ".$arr[$i];
     else
        $result .= " and ".$arr[$i];  
}
echo $result;
Sign up to request clarification or add additional context in comments.

3 Comments

Perhaps you don't understand my question and requirement
maybe you can give a complete example of what you want. In your example you need to tell us what input you have and what is the desired output.
Thanks ddsu for your kind help & effort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.