-1
if (mysqli_num_rows($result) > 0) {
function duration() {
    if ($row["duration"] == 0) {
        return "Expired";
    } else if ($row["duration"] > -1) {
        return $row["duration"];
    } else {
        return "Unknown Error";
    }
};

    echo '<table>';
    while($row = mysqli_fetch_assoc($result)) {
        timeLeft();
        echo '<tr><td>' . " Left from event: " .  duration() . '</td></tr>';
    }
    echo '</table>';
} else {
    echo "0 results";
};

mysqli_close($conn); 

I am trying to replace 0 with "Expired", but with this code it replaces all tables.

Instead of:

Left from event: Expired
Left from event: 3

I get:

Left from event: Expired
Left from event: Expired
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Klajdi
  • 337
  • 1
  • 10
  • 4
    Possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Qirel Jun 07 '16 at 18:47

1 Answers1

0

You need to pass $row into the function:

function duration(array $row) {
    if ($row["duration"] == 0) {
        return "Expired";
    } else if ($row["duration"] > -1) {
        return $row["duration"];
    } else {
        return "Unknown Error";
    }
}

and call it with duration($row)

As a full example,

$rows = [
    [ 'duration' => 0 ],
    [ 'duration' => 2 ],
    [ 'duration' => 3 ],
    [ 'duration' => 4 ]
];

function duration(array $row) {
    if ($row["duration"] == 0) {
        return "Expired";
    } else if ($row["duration"] > -1) {
        return $row["duration"];
    }
}

foreach ($rows as $row) {
    $duration = duration($row);
    echo "Left from event: {$duration}\n";
}

produces

Left from event: Expired
Left from event: 2
Left from event: 3
Left from event: 4
Tyler Sebastian
  • 9,067
  • 6
  • 39
  • 62