Steven Steven - 4 years ago 149
PHP Question

Unexpected else error in syntax?

I have the following code that keeps giving me an "unexpected else" error. Does anyone see something that I missed that is jacking with the syntax?

<?php
$salesman = json_decode($invoice['salesman'], true);
if(empty($salesman)){
for($i = 1; $i <= 5; $i++) {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'"/> '.$i.'<br>';
} else {
foreach($salesman as $k => $v) {
$i = $k+1;
if($v == "checked" {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" checked/> '.$i.'<br>'; // if checked, check.
} else {
echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'"/> '.$i.'<br>'; // if not checked, don't check.
}
}
}

Answer Source
for($i = 1; $i <= 5; $i++){
            echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'"/> '.$i.'<br>';

You are missing a } after the for loop.

Corrected code:

<?php
$salesman = json_decode($invoice['salesman'], true);
if (empty($salesman)){
    for($i = 1; $i <= 5; $i++){
        echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'"/> '.$i.'<br>';
    }
} else {
    foreach($salesman as $k => $v){
        $i = $k+1;
        if ($v == "checked") {
            echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'" checked/> '.$i.'<br>'; // if checked, check.
        } else {
            echo '<input type="checkbox" name="data-invoice-salesman[]" value="'.$i.'"/> '.$i.'<br>'; // if not checked, don't check.
        }
    }
}

You also missed a ')' after $v == "checked" in the if-condition. Fixed that for you too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download