Search code examples
phparraysarray-reverse

Array_reverse "again"


This is my first post, so please be indulgent/lenient.

This array is steps enumeration of an embroidery program

And I have to keep "0" values between not null steps and to do not take null values after

$oldArray = Array
("1278","1297","1278","1000","0","1000","1212","1001","1212","1278","1000",
"0","1297","1001","1000","0","1001","1278","1000","1001","1001","1278", 
"0","1000","1001","0","0","0","0","0","0","0","0","0","0",
"0","0","0","0","0","0","0","0","0","0","0","0","0","0"
);

I reverse it a first time and find the first not null value :

$arrayReversed = array_reverse($oldArray);  

$lastKey = 48;

foreach ($arrayReversed as $key => $value) {
    # If the value is not empty 
    if (!empty($value)) {

[FR] -> remplir un nouveau tableau avec les valeurs en partant de l'index "$key" jusqu'a "$lastKey"

[ENG] -> fill a new array with values starting from the first key with not null value to the last key Edit : Here was my error

        $sequencesFromEnd[] = array_slice($arrayReversed,$key,$lastKey);

I have it corrected with this code :

        $sequencesFromEnd = array_slice($arrayReversed,$key,$lastKey);
        break;

    }
    $key++;
}

Edit : Then It works like I've expected !

Then I want to Reverse "again" the array with values for have steps in the right order and this code is not working :

//First try

$stepsInRightOrder = array_reverse($sequencesFromEnd);

// Second try

//array_reverse($stepsInRightOrder);

Second try commented because it is a no-op.

Unfortunately, the array stay like it is implemented in the "foreach" loop ...

Thanks a lot by advance !!


Solution

  • You are actually not reversing the array. The first array_reverse reverses the array as

    0-> 1278
    1-> 1297
    2-> 1278
    3-> 1000 etc...
    

    After the first array_reverse $arrayReverse contains

    etc...
    0-> 1000
    1-> 1278
    2-> 1297
    3-> 1278
    

    Please note, that only the values in the array are reversed, since you don't explicitly preserve keys. Then you go through with a foreach cycle, where if the value is not empty, you put a new array, which is from the current key to key+48 element into a new array, which means you actually have an array in an array, then break to leave the foreach cycle, so the array will only contain ONE array, which then you reverse, but since it only contains one array, it's the same backwards:

    0-> etc...
        0-> 1000
        1-> 1278
        2-> 1297
        3-> 1278
    

    You only reverse the outer array, which holds 1 element.

    (It was a bit unclear... so $sequencesFromEnd[] actually adds an array into a new array. You might want to use simply $sequencesFromEnd = array_slice(...), or array_reverse($sequencesFromEnd[$some_key]) )