Search code examples
phparraysformsarray-difference

Why does array_diff act differently when array from an input form?


I have this input form:

<form method="POST" action="unique_value_processor.php">
<textarea cols="50" rows="8" name="usedurls"></textarea>
<textarea cols="50" rows="8" name="freshurls"></textarea>
<textarea cols="50" rows="8" name="filteredurls"></textarea>
<input type="SUBMIT" value="SUBMIT">

The files that processes the form is

$old_urls_exploded = explode("\n", $_POST['usedurls']);
$new_urls_exploded = explode("\n", $_POST['freshurls']);
$arraydiff = array_diff($new_urls_exploded, $old_urls_exploded);
print_r($arraydiff);

So when I input the following into the form:

box 1 (old_urls_exploded):

blue, yellow

box 2 (new_urls_exploded):

yellow, blue, banana

then it SHOULD return only:

banana

But array_diff returns:

yellow, banana

Then when you manually type the array as:

$old_urls_exploded = array('blue','yellow');
$new_urls_exploded = array('yellow','blue','banana');

then array_diff returns only:

banana

as it should..

Why does the form affect how array_diff behaves? Am I doing something wrong?


Solution

  • As mentioned by @Rizier123 the problem was white spaces added when the form was input.

    So it was solved using:

    $arraydiff = array_diff(array_map("trim", $new_urls_exploded), array_map("trim", $old_urls_exploded));

    Thank you