Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join string after last array value?

Tags:

arrays

php

I am trying to generate a string from an array. Need to concatenate the array values with a small string AFTER the value. It doesn't work for the last value.

$data = array (
  1 => array (
    'symbol' => 'salad'
  ),
  2 => array (
    'symbol' => 'wine' 
  ),
  3 => array (
    'symbol' => 'beer'
  )
);

$symbols = array_column($data, 'symbol');
$string_from_array = join($symbols, 'bar');
echo($string_from_array);

// expected output: saladbar, winebar, beerbar
// output: saladbar, winebar, beer

like image 644
creatingbigthingsinsmallsteps Avatar asked Jan 27 '23 08:01

creatingbigthingsinsmallsteps


1 Answers

You can achieve it a few different ways. One is actually by using implode(). If there is at least one element, we can just implode by the delimiter "bar, " and append a bar after. We do the check for count() to prevent printing bar if there are no results in the $symbols array.

$symbols = array_column($data, "symbol");
if (count($symbols)) {
    echo implode("bar, ", $symbols)."bar";
}
  • Live demo at https://3v4l.org/ms5Ot
like image 119
Qirel Avatar answered Jan 29 '23 21:01

Qirel