php - Foreach loop is always catching last item, I want to show those items in button from first

I would like to change the value of action attribute of form tag when stock is "0". When the stock is 0, it should show go to the next product ID and set new URL of next product through foreach loop. I am generating dynamic value by using this variable - $value.

First time my code worked perfectly but after inventory is 0 it has gone to last item and never rotating to the first item. I just did the task as trial so want to start from first again. 12, 944, 993 are the IDs of the products I added using woo commerce. 93 is the last product for this URL - http://localhost/wordpress/product/22q2-prime993 . I just want to rotate the loop from first but it's not rotating and always opening the last product when I click on button. Here is my full code -

function btn_shortcode(){
    
$link_url = array (12, 944, 993);
    foreach ($link_url as $value) {
        $increment = 0;
        $productt = wc_get_product( $value);
        $qtyy = $productt->get_stock_quantity();
        if($qtyy == 0) return;
        if($increment == 1)return;  
            $increment++;   
}

$url = "http://localhost/wordpress/product/22q2-prime";


 ?>

<form class="cart" action="<?php echo $url . $value; ?>" method="post">
<div class="quantity">
<label class="screen-reader-text" for="quantity_6332f81bdfee0">22Q2 - Prime - 2 quantity</label>
<div class="bs-quantity">
<div class="qty-nav">
<div class="quantity-button quantity-down limit">-</div>
</div>
<input type="number" id="quantity_6332f81bdfee0" class="input-text qty text" step="1" min="1" max="2" name="quantity" value="1" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric" aria-labelledby="22Q2 - Prime - 2 quantity">
<div class="qty-nav">
<div class="quantity-button quantity-up ">+</div>
</div>
</div>
</div>

<button type="submit" name="add-to-cart" value="12" class="single_add_to_cart_button button alt">Join Now</button>

</form>

        
<?php
 
}

add_shortcode('sc_btn','btn_shortcode');

Answer

Solution:

I can see your $increment variable is initially set to 0. There's no way it'll ever turn to a 1 for the IF condition to work. You could use the for function and count() to know number of records in array, that way it would be easy to loop with the increment variable too. But there's not enough clue on your issue to me on what you want exactly. My observation is with the $increment variable

Source