I would like to conditionally execute two functions:
while($row = mysql_fetch_assoc($result))
(strtolower($message) == $row['question'])
? msg($row['answer']) && update($row['question'])
: '';
but this code is not working.
Is there any reason why you need to use the shorthand code to do this?
The following would be rather more readable and also when you (or someone else) comes to update/change/review/debug the code sometime in the future it will be much more obvious what the intended outcomes were.
while($row = mysql_fetch_assoc($result)) {
if (strtolower($message) == $row['question']) {
msg($row['answer']);
update($row['question']);
}
}
Usually the shortnened ?: version is reserved only for the very simplest conditions and actions.
Define a function msg_update()
that wraps msg()
and update()
:
function msg_update($row) {
msg($row);
update($row);
}
Then you can do:
while($row = mysql_fetch_assoc($result)) (strtolower($message) == $row['question']) ? msg_update($row['answer']) : '';
This is because a tenary operator takes only simple operations. Hope that works for you.
Shorthand only works for one-line statements. Since your if statement contains two lines, shorthand does not work. Usually while loops are formatted as follows:
while (/* condition */)
{
// code to be executed
}
Your ternary expression is also incorrect; it should be written as follows:
(/* condition */) ? /* if true do this */ : /* if false do this */
In the second part of the ternary statement (?:
), you use the conditional operator &&
, which compares two boolean expressions. As I understand it, your intention of the use of &&
is to execute two lines, which is incorrect. Refer to the documentation: PHP Docs (Comparison operators)
You need to write the while loop with braces, because your if statement contains multiple lines of code, as follows:
while($row = mysql_fetch_assoc($result))
{
if (strtolower($message) == $row['question'])
{
msg($row['answer']);
update($row['question']);
}
}