1

Let's say I have a function like this:

function z($zzz){
   for($c=0;$c<5;$c++){
   $zzz[$c]= 10;  
   //more and more codes
   }    
}

I want to write a loop so that

the 1st time the function is executed, argument $array is passed

the 2nd time : argument $array[0] is passed

while the 3rd time : argument $array[1] is passed

.....

and the 12th time : argument $array[0][0] is passed

This is what comes to my mind:

$a = -1;
$b = -1;
$array = array();

while($a<10){
    while($b<10){
         z($array);
         $b++;
         $array= &$array[$b];
    }
    $a++;
    $array= &$array[$a];  
}

I've tried it but it didn't work..

I would appreciate if someone can provide a solution..

9
  • It will be difficult to provide a solution because we have no idea what you are doing. Try to explain it better. Commented May 11, 2012 at 8:09
  • And know that indenting code within control structures (while loops etc) makes it soooo much easier to read Commented May 11, 2012 at 8:11
  • yes, please explain it better Commented May 11, 2012 at 8:12
  • Your function z() is modifying the array but it's not returning anything. Follow @Jack's answer and make it so that the function takes the reference to the array, not its copy and then try again. Commented May 11, 2012 at 8:14
  • I've rephrased my words I hope it is more comprehensible now. Commented May 11, 2012 at 8:17

2 Answers 2

1

If z() is supposed to change the passed array, your function definition should be:

function z(&$zzz)
Sign up to request clarification or add additional context in comments.

2 Comments

and change ` for($c=0;$c>5;$c++)` to ` for($c=0;$c<5;$c++)`
@dInGd0nG sorry about for($c=0;$c>5;$c++) it was a typo.. And the codes work now! Thanks!!
0
$a = 0;
while ($a < 99)         // <-- edit as applicable
{
   $b = 0
   while ($b < 12)
   {
      if ($b == 0)
      {
         Z($array[$a]);
      } else
      {
         Z($array[$a][$b]);
      }
     $b++;
   }
   $a++;
}

And as stated by Jack you need to pass the $array variable by reference for update. Not too sure what that function is trying to achieve though. If you need to fill an array with a predermined dimension, maybe array_fill could be more useful.

http://www.php.net/manual/en/function.array-fill.php

function z(&$zzz){
   for($c=0;$c<5;$c++){
      $zzz[$c]= 10;  
      //more and more codes
   }    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.