PHP overrides array?

Forgive my vigor again. I have an array with 20 + values ​​in it, and I take every 20 to cram into my database and then cut them from the front of the array. I want to restart the indexes of arrays to 0, but instead it starts at 20, even when I use array_values. I also tried array_merge (array (), $ string) What should I do?

if($x%20 == 0){
    var_dump($string) // original array
    get_string($string, $body, $binary); //puts the 20 string into my db

    for($y=0; $y <20; $y++) //done with the 20 so I'm removing them
        unset($string[$y]);

    array_values($string); //reindex set $string[20] to $string[0] PLEASE!
    var_dump($string); // this is suppose to be reindexed
}

Instead i get

array // original array
  0 => string '----' (length=25)
  1 => string '----' (length=15)
  2 => string '----' (length=27)
  3 => string '----' (length=22)
  4 => string '----' (length=23)
  5 => string '----' (length=21)
  6 => string '----' (length=26)
  7 => string '----' (length=23)
  8 => string '----' (length=24)
  9 => string '----' (length=31)
  10 => string '----' (length=19)
  11 => string '----' (length=22)
  12 => string '----' (length=24)
  13 => string '----' (length=24)
  14 => string '----' (length=25)
  15 => string '----' (length=12)
  16 => string '----' (length=16)
  17 => string '----' (length=15)
  18 => string '----' (length=23)
  19 => string '----' (length=15)
  20 => string '----' (length=16)
  21 => string '----' (length=27)

array //reindexed array? This was suppose to be [0] and [1]
  20 => string '----' (length=16)
  21 => string '----' (length=27)
+3
source share
3 answers

I usually do:

$array = array_values($array);

It looks like you got most of the way - just forgot to assign a new array to the old variable.

+12
source

Assign the return value of the re-indexed array:

if($x%20 == 0){
    var_dump($string) // original array
    get_string($string, $body, $binary); //puts the 20 string into my db

    for($y=0; $y <20; $y++) //done with the 20 so I'm removing them
        unset($string[$y]);

    $string = array_values($string); //reindex set $string[20] to $string[0] PLEASE!
    var_dump($string); // this is suppose to be reindexed
}

, :

for($y=0; $y <20; $y++) //done with the 20 so I'm removing them
            unset($string[$y]);

        $string = array_values($string); //reindex set $string[20] to $string[0] PLEASE!

:

for($y=0;$y<20; $y++)
    array_shift($string);
0

array_shift. , , "" .

In addition, whenever you are dealing with arrays and loops, it’s nice to keep the conscience that the array may be short. That is, I strongly recommend not to code fixed for(... <20 ...), but to use a variable like$end = (count($array) < 20 ? count($array) : 20);

0
source

Source: https://habr.com/ru/post/1779297/


All Articles