Rotate php array position

0

Basically I have to move a position of the array (the position 0 to 1, the 1 to the 2, so on until the last position that moves to the first) Example: Array = 1/5/7/9/14/12 Change of position = 12/1/5/7/9/14 The variable $ num, I use to know the number of positions that the array will have.

<?php

$num=$_POST['num'];

echo 'Contenido del array: ';

for($i=0;$i<$num;$i++){

    $numeros[]=rand(0,100);

    echo $numeros[$i].' | ';

}

echo "<br> <br>";

$ultimo=$numeros[$num-1];

echo 'Nuestro array rotado: ';
for($i=0;$i<$num-1;$i++){
          $numeros[0]=$ultimo;
      echo $numeros[$i]=$numeros[$i].' | ';
} 
echo "<br> <br>";

?>
    
asked by SakZepelin 13.12.2018 в 17:07
source

3 answers

1

The simplest way to do it is as follows:

$nums = [1,2,3,4,5];

// Retiras el último elemento del arreglo.
$last = array_pop($nums);
// Lo insertas en la primera posición.
array_unshift($nums, $last);

// Imprimes su contenido (con fines depurativos).
print_r($nums); // [5,1,2,3,4]

Now that if you want to make it reusable, it encapsulates the functionality:

$nums = [1,2,3,4,5];

/**
 * Recorre los elementos un lugar a la derecha.
 *
 * @see https://es.stackoverflow.com/a/221975/729
 * @param array $array
 */
function array_move_rigth(&$array)
{
    $last = array_pop($array);
    array_unshift($array, $last);
}

array_move_rigth($nums);
array_move_rigth($nums);

print_r($nums); // [4,5,1,2,3]

Documentation:

answered by 13.12.2018 в 17:46
0

You need a temporary variable to save the value that you are going to overwrite. Something like this:

$num=6;

echo 'Contenido del array: ';

for($i=0;$i<$num;$i++){

    $numeros[]=rand(0,100);

    echo $numeros[$i].' | ';

}

echo "<br> <br>";


echo 'Nuestro array rotado: '; 
$temp = $numeros[$num-1];

for($i=0;$i<$num;$i++){
    $temp2=$numeros[$i];
    $numeros[$i]=$temp;
    $temp=$temp2;

      echo $numeros[$i].' | ';
} 
echo "<br> <br>";
    
answered by 13.12.2018 в 17:38
0

Try this code:

$num=$_POST['num'];
echo 'Contenido del array: ';

for($i=0;$i<$num;$i++){
    $numeros[]=rand(0,100);
    echo $numeros[$i].' | ';
}

echo "<br> <br>";

//Creamos un array auxiliar con los mismos valores
$aux = $numeros;

//Ahora los intercambiamos en nuestro array original
$numeros[0] = $aux[$num-1];
$numeros[$num-1] = $aux[0];

echo 'Nuestro array rotado: ';
for($i=0;$i<=$num-1;$i++){
    echo $numeros[$i].' | ';
} 
echo "<br> <br>";
    
answered by 13.12.2018 в 17:19