[Solved] Exclude Towns in PHP (Task)

  

3
Topic starter

Write a PHP script to take two lists of strings (as <textarea>) and exclude from the first list all strings from the second one. Print the output as ordered list of items

1 Answer
2

Here's my solution:

<!DOCTYPE html>
<html>
<head>
    <title>Towns To Exclude</title>
</head>
<body>
 
<?php
if (isset($_GET['towns']) && isset($_GET['townsToExclude'])) {
    $towns = array_map('trim', explode("\n", $_GET['towns']));
    $townsToExclude = array_map('trim', explode("\n", $_GET['townsToExclude']));
    $resultTowns = arrayDifference($towns, $townsToExclude);
    printAsList($resultTowns);
}
 
function arrayDifference(array $arr, array $arrToExclude) : array
{
    $result = [];
    foreach ($arr as $item)
        if (!in_array($item, $arrToExclude))
            $result[] = $item;
    return $result;
}
 
function printAsList(array  $arr)
{
    echo "<ul>\n";
    foreach ($arr as $item)
        echo "<li>$item</li>";
    echo "</ul>\n";
}
 
?>
 
<form>
    <div style="display: inline-block">
        Towns:
        <div><textarea rows="10" name="towns"></textarea></div>
    </div>
    <div style="display: inline-block">
        Towns to exclude:
        <div><textarea rows="10" name="townsToExclude"></textarea></div>
    </div>
    <div><input type="submit" value="EXCLUDE"></div>
</form>
</body>
</html>
Share: