Advertisement
ShadowEmbrace

Array Advanced Operations

Nov 4th, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.27 KB | None | 0 0
  1. <?php
  2.  
  3. $numbers = array_map('intval', explode(' ', readline()));
  4.  
  5. do{
  6.     $input = readline();
  7.     $commands = array_map('trim',explode(' ', $input));
  8.  
  9.     if (strtolower($commands[0]) === 'add'){
  10.         $numbers[] = $commands[1];
  11.     }elseif (strtolower($commands[0]) === 'insert'){
  12.         if (array_key_exists($commands[2], $numbers)){
  13.             array_splice($numbers, intval($commands[2]), 0, intval($commands[1]));
  14.         }else{
  15.             echo 'Invalid index' . PHP_EOL;
  16.         }
  17.     }elseif (strtolower($commands[0]) === 'remove'){
  18.         if (array_key_exists($commands[1], $numbers)){
  19.             array_splice($numbers, intval($commands[1]), 1);
  20.         }else{
  21.             echo 'Invalid index' . PHP_EOL;
  22.         }
  23.     }elseif ($commands[0] === 'Shift' && $commands[1] === 'left'){
  24.         for ($i = 0; $i < intval($commands[2]); $i++){
  25.             $shiftNum = $numbers[0];
  26.             array_shift($numbers);
  27.             $numbers[] = $shiftNum;
  28.         }
  29.     }elseif ($commands[0] === 'Shift' && $commands[1] === 'right'){
  30.         for ($i = 0; $i < intval($commands[2]); $i++){
  31.             array_unshift($numbers, $numbers[count($numbers)-1]);
  32.             array_pop($numbers);
  33.         }
  34.     }
  35. }while ($input !== "End");
  36.  
  37. echo implode(' ', $numbers);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement