简体   繁体   中英

variable create in function call to use it in foreach loop in php

I have a the following code in php:

    foreach($lines as $num=>value){
    fixIndex();
    if ($num <$i)continue;


   function fixIndex(){
   static $i=0;
   static $j=1;
   if($j-$i==60)$i=$i=$i+60;
   $j++;
   return $i;
   }

there is no error in running the program. But the $i seems no affect. When I change it to number, ie 60 it will skip 60 records as I wanted. Can anyone helps me out on this one? Thanks in advance.

Totally wrong and strange for me:

First - it's enough:

$i += 60; or $i = $i + 60; //you wrote $i=$i=$i+60

Second - use (always)

{} and paragraphs like this

if ($j-$i==60) {
  //body here
}

This is not neccessary

return $i;

because you use static var (it's not recommended too). Return is correctly if you assign result of function to variable, ie

$i = fixIndex();

This condition is never satisfied

if($j-$i==60)

because above this you initialize variables $i and $j every time

static $i=0;
static $j=1;

1 - 0 != 60, never ever!

first I am sorry for the type mistake. It really is

if($j-$i==60)$i=$i+60;
$J++;

I agree that return $i; is not necessary. the foreach loop still more code to follow that is why } is not see yet. According to the manual the static only set the $i and $j once. when function exit. $j is increment by 1. so after 60 call to that function. $j-$i==60 should happen. At that time $i should affected and change to 60. My real problem is to change the value of $i that after the fixIndex function very 60 increment of $j. Any help? Thanks very much for the prompt answer. Point it out if I do not explain clear enough for the question. Thanks everyone.

You have syntax error value to $value and foreach not have }

Try this

foreach($lines as $num=>$value){
   fixIndex();
   if ($num <$i)continue;
}

function fixIndex(){
    static $i=0;
    static $j=1;
    if($j-$i==60)$i=$i=$i+60;
    $j++;
  return $i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM