Search code examples
phparraystraversal

Move array index when a certain index is reached in another array


I have an array of values that I need to hash using different hash algorithms, the hash types array contains all the hashing algorithms name's. I want to switch the hashing algorithm for each set of values from the values array using the hash_rotation value, in this instance, I would like to switch the $hash_types for each 3 values of values array, but the problem is when the $hash_types array is exhausted, I would like to go back to it's first element and use it.

$hash_rotation = 3;

$hash_types = [
'type_1',
'type_2',
'type_3',
'type_4'
];

$values = [
'something goes 1',
'something goes 2',
'something goes 3',
'something goes 4',
'something goes 5',
'something goes 6',
'something goes 7',
'something goes 8',
'something goes 9',
'something goes 10',
'something goes 11'
];

$current_item = 0;

function rotate_hash($index) {

    global $hash_types;
    global $hash_rotation;
    global $current_item;

    if (($index) % $hash_rotation === 0) {
        $current_item++;
        if ($current_item >= count($hash_types))
            $current_item = 0;
    }

}

foreach ($values as $index => $value) {
    rotate_hash($index);
}

Solution

  • It sounds like you need to take advantage of array pointer manipulations with next() and current():

    $i  =   0;
    # Loop values
    foreach($values as $value) {
        # Get the current value of the hash
        $curr   =   current($hash_types);
        # If the count is equal or higher than what you want
        if($i >= $hash_rotation) {
            # Move the pointer to the next key/value in the hash array
            $curr   =   next($hash_types);
            # If you are at the end of the array
            if($curr === false) {
                # Reset the internal pointer to the beginning
                reset($hash_types);
                # Get the current hash value
                $curr   =   current($hash_types);
            }
        }
        # Increment
        $i++;
    
        echo $value.'=>'.$curr.'<br />';
    }
    

    Gives you:

    something goes 1=>type_1
    something goes 2=>type_1
    something goes 3=>type_1
    something goes 4=>type_2
    something goes 5=>type_3
    something goes 6=>type_4
    something goes 7=>type_1
    something goes 8=>type_2
    something goes 9=>type_3
    something goes 10=>type_4
    something goes 11=>type_1