mandaryneks
mandaryneks

Reputation: 47

While loop and if - execute only one time

I have following code:

while($row = mysql_fetch_assoc($result))
{
    if(strtolower($message) == $row['question'])
    {
        msg($row['answer']);
        update($row['question']);
    } else {
        dodaj(strtolower($message), '', 0);
    }
}

and I would like to execute function dodaj(); only one time, not a few times. How to do it? Please help, thank you very much. Greetings.

Upvotes: 0

Views: 2617

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234807

Use a break statement:

while($row = mysql_fetch_assoc($result))
{
    if(strtolower($message) == $row['question'])
    {
        msg($row['answer']);
        update($row['question']);
    } else {
        dodaj(strtolower($message), '', 0);
        break;
    }
}

EDIT: I assumed you meant to stop processing results once dodaj() was called. However, if you mean that you only want to call dodaj() one time, use a flag variable:

$dodajCalled = false;
while($row = mysql_fetch_assoc($result))
{
    if(strtolower($message) == $row['question'])
    {
        msg($row['answer']);
        update($row['question']);
    } elseif (!$dodajCalled) {
        dodaj(strtolower($message), '', 0);
        $dodajCalled = true;
    }
}

Upvotes: 0

Barmar
Barmar

Reputation: 781068

Use a variable to remember if you called dodaj.

$called_dodaj = false;
while($row = mysql_fetch_assoc($result))
{
    if(strtolower($message) == $row['question'])
    {
        msg($row['answer']);
        update($row['question']);
    } elseif (!$called_dodaj) {
        dodaj(strtolower($message), '', 0);
        $called_dodaj = true;
    }
}

Upvotes: 2

Related Questions