PHP Output Buffering Running output buffer before any content



$user_count = 0;
foreach( $users as $user ) {
    if( $user['access'] != 7 ) { continue; }
    <li class="users user-<?php echo $user['id']; ?>">
        <a href="<?php echo $user['link']; ?>">
            <?php echo $user['name'] ?>
$users_html = ob_get_clean();

if( !$user_count ) {
    header('Location: /404.php');
    <title>Level 7 user results (<?php echo $user_count; ?>)</title>

<h2>We have a total of <?php echo $user_count; ?> users with access level 7</h2>
<ul class="user-list">
    <?php echo $users_html; ?>

In this example we assume $users to be a multidimensional array, and we loop through it to find all users with an access level of 7.

If there are no results, we redirect to an error page.

We are using the output buffer here because we are triggering a header() redirect based on the result of the loop