title: Array is not storing data from text file as expected. How to get first word of each line into array using Powershell?
body: <p>Here is my code: </p>
  
  <pre><code>Get-Content 'hist4.txt' | ForEach-Object { $_.split(" ")[0]} | 
     ForEach-Object { 
  
          $rgbArray += $_ 
  
          for( $i = 1; $i -le $rgbArray.length; $i++ ) {
            $rgbA0=$rgbArray[$i]
            $rgbA1=$rgbArray[$i + 1]
  
            //compare A0 and A1...
          }
     }
  </code></pre>
  
  <p>The text file contents:</p>
  
  <pre><code>1 500
  21 456
  33 789
  40 653 
  54 900 
  63 1000 
  101 1203
  </code></pre>
  
  <ol>
  <li>I want to load the text file. <code>Get-Content 'hist4.txt'</code></li>
  <li>It has two elements on each line. I need the first element. <code>ForEach-Object { $_.split(" ")[0]}</code></li>
  <li>I need to store the first element of each line into an array: <code>$rgbArray += $_</code> </li>
  <li>then iterate over each element of the array and do stuff: <code>for( $i = 1; $i -le $rgbArray.length; $i++ )</code></li>
  </ol>
  
  <p>If I use <code>$rgbArray = @()</code>, then the entire list of elements from the <code>split()</code> command are all stored at <code>$rgbArray[0]</code>. This prevents me from looping over them because the array length is only 1, even though there are hundreds of values stored at the 0 location of the array. </p>
  
  <p>If I use <code>$rgbArray +=</code> then I do get the elements to loop. However, this causes each location of the array to be the same as the last location but plus the next character, and not the whole element from the split command. </p>
  
  <p>For example: <code>$rgbArray += $_</code> outputs</p>
  
  <pre><code>$rgbArray[0] = 1
  $rgbArray[1] = 12
  $rgbArray[2] = 121
  $rgbArray[3] = 1213
  $rgbArray[4] = 12133
  $rgbArray[5] = 121334
  </code></pre>
  
  <p><code>$rgbArray = @($_)</code> outputs</p>
  
  <pre><code>$rgbArray[0] = 1 21 33 40 54 63 ....
  $rgbArray[1] = 
  $rgbArray[2] = 
  $rgbArray[3] = 
  $rgbArray[4] = 
  $rgbArray[5] =
  </code></pre>
  
  <p>where I need it to be :</p>
  
  <pre><code>$rgbArray[0] = 1
  $rgbArray[1] = 21
  $rgbArray[2] = 33
  $rgbArray[3] = 40
  $rgbArray[4] = 54
  $rgbArray[5] = 63
  </code></pre>
  
  <p>and so on. </p>
  
  <p>I would like to know if I am not creating the array correctly and how to get the first element of each line as a separate array element?</p>
  
  <p>Later in the code I would like to be able to compare the first element of different lines in the text file to other first elements. </p>