'if' inside 'while' statement in php
17,473
Solution 1
The best way to accomplish this is using ternary operators:
while (whatever)
{
echo 'foo'
.($statement ? 'bar' : '')
.'baz';
}
Solution 2
use:
if ( is_null( $row['media'] ) ) { ... } else { ... }
Author by
njwrigley
Updated on June 04, 2022Comments
-
njwrigley almost 2 years
I have this bit of code which loops through an array and echos out the result to the page thus:
while($row = mysqli_fetch_array($result)) { echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' . '<td>' . $row['provider'] . '</td>' . '<td>' . $row['media'] . "</td></tr><br />\n"; }
It works just fine, but I was hoping to use an 'if' statement on the $row['media'] because it contains some NULL and some !NULL results.
I wanted to be able to echo a different response a little like:
if ($row['media'] != NULL){ echo 'Nope'; } else { echo $row['media']; }
Is this possible in this situation?
Thanks.
-
darkAsPitch over 13 yearsI'm sorry, but I have to disagree. This is not true in the general case, although it is practical for short expression type situations.
-
eykanal over 13 years@DarenThomas: I don't know if I agree with you. I would state it the other way around; this is useful for most situations, but if applied to a too-complex case, it will make a ridiculous mess of your code. For most situations, this can work fine. I edited it to add some whitespace, though.