Home > Net >  How to display array items with another items in one line in php?
How to display array items with another items in one line in php?

Time:07-10

I am getting two arrays as parameters but I want to have one item of array to be display with another item of the array in one line. Can anyone help me, please?

   function getLists($str, array $items,$optional=null, ){
    
            $items1 = array_map(function($x) use ($optional) { return "$x $optional"; }, $items);
            $itemsCount = count($items1);
            $sentence = '';
            if ($itemsCount == 1) {
                $sentence = $items[0] . '.';
            } else {
                if($optional == null)
                {
                    $partial = array_slice($items, 0, $itemsCount-1);
                    $sentence = implode(', ', $partial) . ' and ' . $items[$itemsCount-1]; 
    
                }
                if(is_string($optional))
                {
                    $partial = array_slice($items1, 0, $itemsCount-1);
                    $sentence =   implode(', ', $partial). ' and ' . $items1[$itemsCount-1];
                }
            else
            {
                $partial = array_slice($items1, 0, $itemsCount-1);
                $sentence =   implode(', ', $partial). ' and ' . $items1[$itemsCount-1];
            }              
            }
                        
            return $str.': '.$sentence.'.';
        }

Here are what I am trying to do, the following two are working correctly

getList("What do you want",array("chocolate","icecream","shake"));
getList("Ice Cream has",array("chocolate","vanilla","mango"),"flavour");

But when I replace try to pass [] as parameter then I got an error array to string conversion warning

getList("The color required",array("green","red","blue"),['chilli','onion','berry']);

So when I pass this parameter and my output should be like: I am not getting the correct output that should be like:

The color required: green chilli,red onion and blue berry.

Instead I am getting:

The color required: green Array, red Array and blue Array.

CodePudding user response:

The main issue is that the line

$items1 = array_map(function ($x) use ($optional) { return "$x $optional"; }, $items);

does not cope with anything but passing a single value in for the $optional parameter.

If instead you add a condition which checks if it's an array and (using the key value from a foreach - array_map() doesn't work with keys ATM)...

$items1 = [];
foreach ($items as $key => $value) {
    $items1[] = $value . ' ' . (is_array($optional) ? $optional[$key] : $optional);
}

This will, if optional is an array, return the corresponding elements from that array, or just use the value if not an array.

This gives...

What do you want: chocolate , icecream  and shake . 
Ice Cream has: chocolate flavour, vanilla flavour and mango flavour. 
The color required: green chilli, red onion and blue berry.
  •  Tags:  
  • php
  • Related