How to add automatically bootstrap 4 order-lg-1 and order-lg-2 classes for columns in foreach loop based on the count?

You should use the PHP modulo operator for that. Since you need two different layouts, you should calculate your classes numbers according to $count % 2 and ($count + 1) % 2:

<?php
$count = 0;
foreach ($howtoplaycontent as $hpc): ?>
<div class="row courses_row" style="background-color: #f8f8f8">
    <div class="container">
        <div class="row" style="padding: 15px;">
            <div class="col-lg-6 course_col order-lg-<?php echo $count % 2 + 1; ?>">
            </div>
          
            <div class="col-lg-6 course_col order-lg-<?php echo ($count + 1) % 2 + 1; ?>">
            </div>
        </div>
    </div>
</div>
<?php $count ++;
endforeach; ?>

Update

Since you need a different background color on even and odd rows, I suggest you to define two additional classes in your CSS:

.row.courses_row.odd_row {
    background-color: #f8f8f8;
}
.row.courses_row.even_row {
    background-color: #ffffff;
}

and then use the following code:

<?php
$count = 0;
foreach ($howtoplaycontent as $hpc): ?>
<div class="row courses_row <?php echo $count % 2 ? 'even' : 'odd'; ?>_row">
    <div class="container">
        <div class="row" style="padding: 15px;">
            <div class="col-lg-6 course_col order-lg-<?php echo $count % 2 + 1; ?>">
            </div>
          
            <div class="col-lg-6 course_col order-lg-<?php echo ($count + 1) % 2 + 1; ?>">
            </div>
        </div>
    </div>
</div>
<?php $count ++;
endforeach; ?>