Concatenate variables from an array

Asked

Viewed 774 times

2

I need to concatenate variables from an array, to run an SQL, this array can have differentiated values. If the array is greater than 1, then it must have $variable + $variavel02. If the array is equal to 1. Then play only the variable.

$array_filial = array($f1, $f2, $f3, $f4);

$filiais = '';
foreach ($array_filial as $key => $f) {
      if ($f > 1) {
           $filiais .= "" . $f . "+ ";
      }
      else {
        $filiais .= "" . $f . "";
            }
}

$in_filial = substr($filiais, -0, -2);

If array > 1

$in_filial = $f1 + $f2;

If array = 1

$in_filial = $f1;

SQL

SELECT(CASE WHEN departamento = 1 AND tipo = 1 THEN (" . $in_filial . ") ELSE 0 END) as total from tabela;
  • 1

    tries to use the implode function

  • that your code has error? which??

  • You want to add all array values, correct?

4 answers

3


  • If I understood the question correctly, he wants to separate by "+" and not "," otherwise I even agree with the implode.

  • I changed the answer, but all I had to do was use logic and make the switch, adapt his reality right @Dudaskank

  • It works, but when you have at least 2 records with data

  • With a single record he brings only the same

2

The best solution to your problem would be to use the function implode()

example using implode():

if(count( $array ) == 1)
{
    $str = implode("+", $array);
}else{
    $str = $f1 . "+" . $f2;
}

2

To make it more general, try the loop thus:

$filiais = '';
foreach ($array_filial as $key => $f) {
      if ($filiais != '')
           $filiais .= "+ ";

      $filiais .= $f;
}
  • 2

    $filiais = substr($filiais, 0, -2);

1

The function implode(), already quoted by colleagues, will do the service as you planned.

But if I understand correctly, you want to add the array values to use in your SQL. If you don’t need to have the values separated and can add the sum first, you can let PHP do this with the function array_sum:

$in_filial = array_sum($array_filial);

Browser other questions tagged

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