Does anyone know of a function that passes the array positions?

Asked

Viewed 26 times

-4

For example, suppose I have the array [1,2,3], change to [2,3,1] and then to [3,1,2]. I’m looking for a function that together the for, can pass the array positions. Ex:

for($i = 0; $i<10; $i++){
  FUNÇÃO
}
  • I’m asking for tips on PHP functions that can help, because I’m really aimless in resolution

1 answer

0

A solution to rearrange the position of an array’s values in this way is to combine array_shift and array_push as follows:

$numeros = array(1, 2, 3);
$primeiro = array_shift($numeros); // Pega o primeiro valor do array
array_push($numeros, $primeiro); // Array push adiciona um valor ao final do array
// ou também $numeros[] = $primeiro faz a mesma coisa que o de cima.

Then put all this into a function to make your life that easy:

public function trocaPosicoes(array $coisas){
    $primero = array_shift($coisas);

    return is_null($primeiro) ? $coisas : array_push($coisas, $primeiro);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.