Lazy Guy
Lazy Guy

Reputation: 101

PHP Array: Loop Array until the value is empty

So, I build a little php array looping. The objective is : the loop will finish when one of array value is empty.

This is the code:

<?php
if(isset($_POST['submit'])) {
   $Var_1 = array('Manggo_1' => rand(1, 3),
                  'Manggo_2' => rand(1, 3),
                  'Manggo_3' => rand(1, 3),
                  'Manggo_4' => rand(1, 3),
                  'Manggo_5' => rand(1, 3),
                  'Manggo_6' => rand(1, 3)
                );

   $Var_2 = array('Manggo_7' => rand(1, 3),
                  'Manggo_8' => rand(1, 3),
                  'Manggo_9' => rand(1, 3),
                  'Manggo_10' => rand(1, 3),
                  'Manggo_11' => rand(1, 3),
                  'Manggo_12' => rand(1, 3)
                 );



  while (!(empty($Var_1) && empty($Var_2))) {


      foreach ($Var_1 as $value) {
            echo "$value, ";
            if ($value == 3) {
                unset($value);
            } elseif ($value == 1) {
                array_push($Var2, $value);
            }
      }

      foreach ($Var_2 as $value) {
            echo "$value, ";
            if ($value == 3) {
                unset($value);
            } elseif ($value == 1) {
                array_push($Var1, $value);
            }
      }
  }
}

So, that's all my php code, If the $value == 3, I want to destroy the value, and if == 1, I want to insert the value to another array. Loop until one of array is empty.

The question is: How to print/echo the result from each loop iteration (after click the submit button), until one of the array value is empty ?? I always get looping forever.

Thanks.

Upvotes: 0

Views: 2233

Answers (2)

Sachin
Sachin

Reputation: 2765

 while (!empty($Var_1) && !empty($Var_2)) {


  foreach ($Var_1 as $key=>$value) {
        echo "$value, ";
        if ($value == 3) {
            unset($Var_1[$key]);
        } elseif ($value == 1) {
            array_push($Var_2, $value);
        }
  }

  foreach ($Var_2 as $value) {
        echo "$value, ";
        if ($value == 3) {
            unset($Var_2[$key]);
        } elseif ($value == 1) {
            array_push($Var_1, $value);
        }
  }
}
}

You are getting looping forever because

  1. The condition in while loop is not correct .(according to your condition the loop will finish only after both the array become empty.)
  2. Problem in unsetting the array variable.
  3. You are pushing values into wrong variables .

Upvotes: 1

jfxninja
jfxninja

Reputation: 381

You aren't unsettling the value from the array, you are just unsetting a local variable within the loop. You can use $key=>$value to obtain a reference back to the looped array like so:

foreach ($Var_2 as $key=>$value) {
        echo "$value, ";
        if ($value == 3) {
            unset($Var_2[$key]);
        } elseif ($value == 1) {
            array_push($Var1, $value);
        }
  }

Upvotes: 0

Related Questions