Return value generated from foreach

Asked

Viewed 196 times

0

Basically, I have this foreach to dynamically create the selection text:

foreach ($table['exists'] as $item) {
            switch ($i) {
                case 0:
                    echo($item.' = "'.$_POST[$item].'" AND');
                    break;

                case $len - 1:
                    echo(' '.$item.' = "'.$_POST[$item].'"');
                    break;

                default:
                    echo(' '.$item.' = "'.$_POST[$item].'" AND ');
                    break;
            }
            $i++;
        }

It returns me basically this:

cep = "{CEP inserido}" AND rua = "Delfinópolis" AND dispo = "1"

If this array is inserted into the function (takes the exists array and compares with the one inserted in the form):

$tabela = ['table'  => 'ceps',
                 'exists' => ['cep', 'rua', 'dispo'] ];

I needed to take this dynamically created value and insert it into a variable to put in my function:

$existe = DBRead($table['table'], "WHERE {$minhaVarEntraAqui}");
  • Concatene, create a variable outside the foreach, and in every condition of switch place $var = ....

  • @Edilson did not understand this solution. May elaborate a little more the answer?

1 answer

1


$i=0;
        $len = count($table['exists']);
        foreach ($table['exists'] as $item) {
            switch ($i) {
                case 0:
                    $marray[0][$i] = $item.' = "'.$_POST[$item].'" AND ';
                    break;

                case $len - 1:
                    $marray[1][$i] = $item.' = "'.$_POST[$item].'"';
                    break;

                default:
                    $marray[2][$i] = $item.' = "'.$_POST[$item].'" AND ';
                    break;
            }
            for ($j = 0; $j < 3; $j++)
                echo $marray[$j][$i];
            $i++;
        }

I believe this will solve the problem

Browser other questions tagged

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