Skip to content
Advertisement

How to add serial number column in this PHP script? [closed]

I am not able to output serial number in this php script. Trying to add serial number for each of the products fetched from woocommerce data.

<?php 
$args = array(
    'status' => 'publish',
    'limit' => 100,
    'orderby' => 'title',
    'order'   => 'ASC'
);
$products = wc_get_products( $args );
$counter = 0;

if (count($products)) {     
    // Open the table
    echo "<table style = 'background-color:#ffffff;border-collapse: collapse;'><thead><tr>
            <th width='40' style='border:1px solid black'>Sl No.</th>
            <th width='400' style='border:1px solid black'>Product Name</th>
            <th style='border:1px solid black' width='54'>Stock</th>
            </tr></thead>";
    // Cycle through the array
    foreach ($products as $product) {
        // Output a row
        echo "<tr>";
        echo "<td style='border:1px solid black'>$counter++</td>";
        echo "<td style='border:1px solid black'>$product->name</td>";
        echo "<td align='center' style='border:1px solid black'>$product->stock_quantity</td>";
        echo "</tr>";
    }

    // Close the table
    echo "</table>";
}


?>

Advertisement

Answer

PHP can’t parse increments in strings, so you have to increment $counter explicitly:

$counter++;
echo "<td style='border:1px solid black'>$counter</td>";
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement