Foreach循环不附加到数组

As you can see below, I am going through an array called $subLinks, taking each as a $subLink, and adding it to the array called $linkArray, if it is not already there.

However on each iteration of the loop, $linkArray is cleared and starts from the beginning. So for example at the end of each loop $linkArray echos a list of links, and on the second loop that list of links is cleared and replaced with the links of the next $subLink.

My aim is to end up with one big array containing every $subLink - without duplicates,

    $linkArray = array();
    foreach($subLinks as $subLink){

      # Validate and clean the links found
      $subLink = cleanUrl($url,$subLink);

      if(!in_array($subLink,$linkArray)){
        $linkArray[2] = $subLink;
      }

      echo($linkArray[2].'<br />');
      flushOutputBuffer();

    }

An example of what is echoed is:

link1
link2
link3

At the next loop, this is echoed:

link1
link2
link3

What I'd like, is if it's not a duplicate, to add to the array, like this

link1
link2
link3
link4
link5

Any help really appreciated here,

Thanks

Update: The array seems to reset after 110 elements, and overwrites previous entries

You are always assigning the new link to [2] and overwrite the contents of [2] again and again and again, try this instead:

//...
if(!in_array($subLink, $linkArray)){
    $linkArray[] = $subLink;
}
//...

This will append the new link to the end of an array.

You are not adding the items correctly. To populate an array, you would need to write

$linkArray[] = $subLink; // do not specify an index

Of course this is all moot, because there is a much, much better way of achieving the same result:

$linkArray = array_unique(array_map(
                 function($item) use($url) { return cleanUrl($url, $item); }, $subLinks
             ));

Um, because you're overwriting it in each loop? You write to the same index over and over again

If you want to append to the index, do it like this:

$yourVar[2][] = $valueToAppend

You want to get rid of duplicate entries, first just add every sublink to the link array; then simply use the function below to get rid of any duplicates. It's a one step process and one of the fastest ways to get unique data in your array.

The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.

Syntax

Array = array_unique(array)

In the end you'll have 'one big array containing every $subLink - without duplicates'.

And thats that. Hope this helps, if so let me know.

Pk