magicianiam
magicianiam

Reputation: 1579

Cannot array_unique merged arrays created differently and displays differently

I have this two arrays.

one is generated using a standard SELECT query, the other one is generated using this statement:

$file = file(DOC_ROOT."robots.txt");
foreach($file as $text) {
$test[] = $text;
}

the first array output like this:

Array
(
    [0] => Disallow: /admin/
    [1] => Disallow: /m/
    [2] => Disallow: /private/
)

the other like this:

Array
(
[4] => Disallow: /admin/

[5] => Disallow: /m/

[6] => Disallow: /private/

[7] => Disallow: /success.php
)

the problem now is that after merging the two arrays, array_unique doesn't work, im guessing maybe its caused by the spaces generated by the second array, i've tried removing them but with no luck. now my question is, is it really the spaces that cause this or is there something wrong with my flow? for your convenience here is the array code, not that it would matter that much. How will i be able to solve this problem? Thank you.

$result = array_merge($lines,$test);
    $result = array_unique($result);
    echo '<pre>';
    echo print_r($result);
    echo '</pre>';

the result:

Array
(
[0] => Disallow: /admin/
[1] => Disallow: /m/
[2] => Disallow: /private/

[32] => 

[33] => Disallow: /admin/

[34] => Disallow: /m/

[35] => Disallow: /private/

[36] => Disallow: /success.php
)

Upvotes: 1

Views: 54

Answers (1)

dynamic
dynamic

Reputation: 48131

array_unique() works on array's values. In your example there aren't any value in common so it will not delete any values.

And yes spaces make array_unique see 2 different values, so basicalyl these 2 values are not the same:

[0] => 'hello1   hello2'
[1] => 'hello1 hello2'

and array_unique leaves both values

You have that space between keys within pre because file() keeps \n and \r. So do a:

file(,FILE_IGNORE_NEW_LINES);

Upvotes: 1

Related Questions