1

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 ."
Barmar
  • 741,623
  • 53
  • 500
  • 612
ku234
  • 71
  • 6

2 Answers2

0

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.'.';
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks. Just a quick help, what if we have $optional as an array like ["best","good","bad"] instead $optional = "flavor". – ku234 Jul 08 '22 at 21:43
  • How should the array be used in that case? – Barmar Jul 08 '22 at 21:46
  • If you want to loop over all the arrays together, you can pass multiple arrays to `array_map()`. The corresponding elements of each array will be arguments to the function. `array_map(function($x, $option) { ... }, $items, $optional)` – Barmar Jul 08 '22 at 21:47
0
    $str = "Ice Cream has: ";
    $optional= "flavor";
    $items = array("vanilla","chocolate","mango");
    $count = count($items);
    $c=0;
    if ($count == 1) {
        $str .= $items[0] . ' '.$optional.'.';
    } else {
        foreach( $items as $item){
            
            $c++;
               
            if( $c == $count){
                $str = $str.' and '.$item.' '.$optional.'.';
            }else if($c == $count-1){
                $str = $str.$item.' '.$optional.'';
            }else{
                $str = $str.$item.' '.$optional.', ';
            }
        }
    }
               
    return $str;
Mustafa
  • 87
  • 1
  • 8