0

I have the following PHP function where I am trying to explode an array and apply foreach loop on it to get a collective set of data. However, I am getting the error quoted in the subject.

function getSwipableUsers() {
  $expInt = explode(',', $f['interests']);

  $userDisplayData = array();
  foreach($expInt as $ints){
    $userDisplayData[] = "<div class='tag alert-primary'>".$ints."</div>";
  }

  $html = '<div class="user-distance mt-2">'.$userDisplayData.'</div>';
  return $html;
}

I rechecked again and again but everything seems fine to me. What's wrong with my code here?

Shubham Jha
  • 97
  • 10
  • `$userDisplayData` is an array which you try to string concatenate in `$html = '
    '.$userDisplayData.'
    ';`
    – Remy Jun 19 '21 at 15:50
  • Yes, I see that. What's the fix? – Shubham Jha Jun 19 '21 at 15:51
  • You could define `$userDisplayData` as a string and concatenate those divs to it or use [implode](https://www.php.net/manual/en/function.implode.php) with an empty string separator to convert the array to a string. – Remy Jun 19 '21 at 15:52
  • 1
    @Remy got it.. Thanks :) – Shubham Jha Jun 19 '21 at 15:54
  • Instead of pushing `"
    ".$ints."
    "` to `$userDisplayData[]`, concatenate these strings to `$html` directly or else re-iterate the `$userDisplayData` and append all strings to `$html`
    – Haridarshan Jun 19 '21 at 15:55
  • @Haridarshan if you see my comment right above yours, I actually figured it out. But thanks for your time :) – Shubham Jha Jun 19 '21 at 16:34

1 Answers1

1

As stated above, the $userDisplayData variable is an array, and you are trying to assign a string space to it.

You could do it this way:

function getSwipableUsers() {
    $expInt = explode(',', $f['interests']);
  
    $userDisplayData = '<div class="tagsection">';

    foreach($expInt as $ints){
      $userDisplayData .= "<div class='tag alert-primary'>".$ints."</div>";
    }

    $userDisplayData .= '</div>';

    $html = '<div class="user-distance mt-2">'.$userDisplayData.'</div>';

    return $html;
}
Shubham Jha
  • 97
  • 10
  • 1
    I already figured it out after @Remy hinted about concatenating. But accepting your answer to let others know that this is the right approach which I used. – Shubham Jha Jun 19 '21 at 16:36