Grouping Array Results out of Loop

Asked

Viewed 78 times

2

How I Group Array Results out of Loop into a Single Variable

  • In the example below the result that is inside the loop is correct but I need that same result to appear on the outside of the loop,

How can I make it work

      foreach ($ids_cotados as $value) {
      echo $ids_cotados = $value.','; // 520, 130, 60, 700,

      }
      echo $ids_cotados;   // aqui da erro só pega 520,
  • vc want an array or string at the end?

  • I want it to come out like 520, 130, 60, 700

2 answers

2

To do this, the best way is with the implode(), it concatenates everything and puts a string in the middle of each array value, in case the ',', would look like this:

$stringconcatenada = implode(",", $ids_cotados);

1


When wearing something like $var = $novo within a loop what happens is at each loop/iteration the value of $var will be overwritten and after the loop will have the last value.

If you want to take array elements and separate them by commas you can use the function implode() in that case.

$arr = array(1,20,30,60,35);
echo implode(',', $arr);

Exit:

1,20,30,60,35
  • didn’t work.... only shows "Array" my array comes from a post like this Array ( [0] => 520 [1] => 130 [2] => 60 )

  • @Could Fabiohenrique put the following question: print_r() of $ids_cotados ?

  • exactly print_r() gave returns like this Array ( [0] => 520 [1] => 130 [2] => 60 )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.