I want to add variables with each array item but I do not have clue what to do? Here is my code. Can anyone help me, please? Thanks
$str = "Ice Cream has";
$optional= "flavor";
$items = array("vanilla","chocolate","mango");
$itemsCount = count($items);
$sentence = '';
if ($itemsCount == 1) {
$sentence = $items[0] . '.';
} else {
$partial = array_slice($items, 0, $itemsCount-1);
$sentence = implode(', ', $partial).' '. $optional. ' and ' . $items[$itemsCount-1];
}
return $str.': '.$sentence.'.';
I want an output should be:
"Ice Cream has: vanilla flavor, chocolate flavor and mango flavor."
But I am getting output:
"Ice Cream has: vanilla, chocolate flavor and mango ."
CodePudding user response:
You need to concatenate $optional
to all elements of the array, not just the result of implode()
. You can use array_map()
to create a new array with $optional
added to each element.
$str = "Ice Cream has";
$optional= "flavor";
$items = array("vanilla","chocolate","mango");
$items1 = array_map(function($x) use ($optional) { return "$x $optional"; }, $items);
$itemsCount = count($items1);
$sentence = '';
if ($itemsCount == 1) {
$sentence = $items[0] . '.';
} else {
$partial = array_slice($items1, 0, $itemsCount-1);
$sentence = implode(', ', $partial). ' and ' . $items1[$itemsCount-1];
}
return $str.': '.$sentence.'.';
CodePudding user response:
$str = "Ice Cream has";
$optional= "flavor";
$items = array("vanilla","chocolate","mango");
$count = count($items);
$res="Ice Cream has: ";
$c=0;
if ($count == 1) {
$res .= $items[0] . ' flavor.';
} else {
foreach( $items as $item){
$c ;
if( $c == $count){
$res = $res.' and '.$item.' flavor.';
}else if($c == $count-1){
$res = $res.$item.' flavor ';
}else{
$res = $res.$item.' flavor, ';
}
}
}
return $res;