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

Q: Exclude Towns in PHP (Task)

+3 votes

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

asked in PHP category by user hues
retagged by user golearnweb

1 Answer

+1 vote
Best answer

Here's my solution:

<!DOCTYPE html>
    <title>Towns To Exclude</title>

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);

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";


    <div style="display: inline-block">
        <div><textarea rows="10" name="towns"></textarea></div>
    <div style="display: inline-block">
        Towns to exclude:
        <div><textarea rows="10" name="townsToExclude"></textarea></div>
    <div><input type="submit" value="EXCLUDE"></div>


answered by user icabe
selected by user golearnweb