André Castro
André Castro

Reputation: 1565

PHP - foreach returning duplicate entries

I have a foreach loop returning duplicate entries from a array string without duplicates inside it.

The code:

$a = [];
        $b = [];
        foreach($categories['results'][0]['parameters'] as $key => $value) {
            if(in_array($value['code'], $input_valid_names)) {
                if($value['type'] == 'input') {
                    $a = $value['code'];
                    $b = $PostData[$value['code']];
                }
                if($value['type'] == 'select'){
                    $a = $value['code'];
                    $b = $PostData[$value['code']];
                }
                if($value['type'] == 'checkbox' && !empty($PostData[$value['code']])){
                    $a = $value['code'];
                    $b = 'Sim';
                }
                $param[] = [$a => $b];
            }
        }

Any idea why its doing it? Made several debug but no clue...

Upvotes: 0

Views: 1489

Answers (3)

André Castro
André Castro

Reputation: 1565

Solved it, putting:

$param[] = [$a => $b];

inside every if validation. No more duplicate values inside $param array.

Upvotes: 0

Dmytro Huz
Dmytro Huz

Reputation: 1554

Because when $value['type'] not equal for any if statement your code sets in $param previous $a/$b value. Try this:

    $param = [];
    foreach($categories['results'][0]['parameters'] as $key => $value) {
        $a = false;
        $b = false;
        if(in_array($value['code'], $input_valid_names)) {
            if($value['type'] == 'input') {
                $a = $value['code'];
                $b = $PostData[$value['code']];
            }
            if($value['type'] == 'select'){
                $a = $value['code'];
                $b = $PostData[$value['code']];
            }
            if($value['type'] == 'checkbox' && !empty($PostData[$value['code']])){
                $a = $value['code'];
                $b = 'Sim';
            }
            if($a and $b){
                $param[] = [$a => $b];
            }
        }
    }

Upvotes: 2

Exterminator
Exterminator

Reputation: 1246

$a = '';
    $b = '';
    $param = array();
    foreach ($categories['results'][0]['parameters'] as $key => $value) {
        if (in_array($value['code'], $input_valid_names)) {
            if ($value['type'] === 'input') {
                $a = $value['code'];
                $b = $PostData[$value['code']];
            }else if ($value['type'] === 'select') {
                $a = $value['code'];
                $b = $PostData[$value['code']];
            }else if ($value['type'] === 'checkbox' && !empty($PostData[$value['code']])) {
                $a = $value['code'];
                $b = 'Sim';
            }
            $param[] = [$a => $b];
        }
    }

Upvotes: 0

Related Questions