Search code examples
phpparsingif-statementcastingint

Parse error while comparing int values in a if statement


Currently I am working on a function that should change the pos values (int values) of an array like this one:

$comb = array(
    'A' => array('pos' => 3, 'lett' => 'C'),
    'B' => array('pos' => 4, 'lett' => 'D'),
    );

The function that should perform what i need is the following one:

function change($comb) {
    foreach ($comb as $value) {
        if($value['pos']== 1) {
            $value['pos'] = 4;
        } else {
            $value['pos']--;
        }
    }
}

I can not understand why during the execution of the code, an general parse error occurs at the line of the if condition. I tried casting $comb ['pos'] in int, but this does not seem to solve the problem.

Any idea?


Solution

  • If you really want to change $comb you should pass it as a reference (the & sign in parameters)

    function change(&$comb) {
        foreach ($comb as $key => $value) {
            if($value['pos']== 1) {
                $comb[$key]['pos'] = 4;
            } else {
                $comb[$key]['pos']--;
            }
        }
    }