1

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
)

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

the first one is just an example, both arrays contain the same values, let me edit the question to avoid confusion, sorry about that. :)
@magicianIam: yea i got that so i have edited to add space information
what i meant about the spaces was the ones in between array indexes, is that even relevant to array_unique? i have been wondering what caused such spaces. thanks.
@magicianIam: that's because FILE adds carriage return or new line at the end of values
so use FILE_IGNORE_NEW_LINES as second param of file()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.