Concatenating variables from an array

2

I need to Concatenate variables of an array, to execute a 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 just play 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;
    
asked by anonymous 10.08.2017 / 15:44

4 answers

3

Use implode ()

if(count( $array ) == 1)
{
    $str = implode("+", $array);

}

Documentation: link

    
10.08.2017 / 15:57
2

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

example using implode ():

if(count( $array ) == 1)
{
    $str = implode("+", $array);
}else{
    $str = $f1 . "+" . $f2;
}
    
10.08.2017 / 16:00
2

To make it more generic, try loop like this:

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

      $filiais .= $f;
}
    
10.08.2017 / 16:01
1

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

But if I get it right, you want to add the array values to use in your SQL. If you do not need to have the values separated and you can do the sum before, you can let PHP do this with the array_sum function: / p>

$in_filial = array_sum($array_filial);
    
10.08.2017 / 16:16