Search code examples
phplaravelimplode

PHP implode function error, does not include implode string


I'm using laravel 5.8 and am trying to get a foreach to implode

foreach($stocks->currency as $currency)
{
  $d1 = $currency->cost;
  $d2 = $currency->currency->name;
  $currencies = array(' ' . $d1 . ' ' . $d2);
  echo implode("or", $currencies);
}

Is my code block

However, this returns the following :

enter image description here

clearly this lacks the "or" that the implode should add

Thank you in advance!


Solution

  • try something like

    $currencies = [] // Create an empty array
    foreach($stocks->currency as $currency)
    {
      $d1 = $currency->cost;
      $d2 = $currency->currency->name;
      $currencies[] = ' ' . $d1 . ' ' . $d2; // Add a new value to your array
    }
    echo implode("or", $currencies); // implode the full array and separate the values with "or"