settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Change Array - PHP Array Task

+4 votes

Write a program, which reads an array of integers from the console and receives commands, which manipulate the array. Your program may receive the following commands: 

  • Delete {element} – delete all elements in the array, which are equal to the given element
  • Insert {element} {position} – insert element and the given position

You should stop the program when you receive the command Odd or Even. If you receive Odd : print all odd numbers in the array separated with single whitespace, otherwise print the even numbers.

Examples:

change array php array task

asked in PHP category by user golearnweb

1 Answer

+3 votes

Here is my solution:

<?php

$arr = explode(" ", readline());

$input = readline();

while (true) {

    $args = explode(" ", $input);
    $command = $args[0];

    if ($command == "Delete") {
        $element = $args[1];
        while (array_search($element, $arr) !== false) {
            $index = array_search($element, $arr);
            array_splice($arr, $index, 1);//remove
        }
    } else if ($command == "Insert") {
        $element = $args[1];
        $position = $args[2];
        if ($position >= 0 && $position <= count($arr)) {
            array_splice($arr, $position, 0, $element);//replace
        }
    }


    if ($input == "Odd" || $input == "Even") {
        $reminder = 0;
        if ($input === "Odd") {
            $reminder = 1;
        }
        for ($i = 0; $i < count($arr); $i++) {
            if ($arr[$i] % 2 == $reminder) {
                echo "$arr[$i] ";
            }
        }

        echo PHP_EOL;
        break;
    }

    $input = readline();
}
answered by user Jolie Ann
...