title: PHP: Sort array by exploded value
body: <p>How can I sort an array by a value from an exploded string?</p>
  
  <p>To make it a bit more clear, I have data stored in a textfile in the following format:</p>
  
  <pre><code>Value_1|Value_2|Value_3|Value_4|Value_5
  Value_1|Value_2|Value_3|Value_4|Value_5
  Value_1|Value_2|Value_3|Value_4|Value_5
  ...
  </code></pre>
  
  <p>I read the data using</p>
  
  <pre><code>$data_file = 'foo.txt';
  $lines = file($data_file, FILE_IGNORE_NEW_LINES);
  </code></pre>
  
  <p>then explode each line and output the content (HTML stripped to keep it clean)</p>
  
  <pre><code>foreach ($lines as $line_num =&gt; $dataset) {
    $dataset = explode('|', $dataset);
    //echo exploded values + some HTML
  }
  </code></pre>
  
  <p>However, before I output the data, I want to sort the array by Value_2 (which is always a number) from e.g. high to low. Do I have to set the keys of the array to Value_2 and then sort it? How can I do that? What would be the best solution here?</p>
  
  <p>Thanks for your help!</p>
  
  <hr>
  
  <p>This is the final, slightly modified snippet for everyone who's interested:</p>
  
  <pre><code>$data_file = 'foo.txt';
  $lines = file($data_file, FILE_IGNORE_NEW_LINES);
  
  function sort_data_array($a, $b){
      $ex_a = explode('|', $a);
      $ex_b = explode('|', $b);
      if ($ex_a[1] == $ex_b[1]) {return 0;}
      return ($ex_a[1] &gt; $ex_b[1]) ? -1 : 1;
  }
  
  uasort($lines, 'sort_data_array');
  $lines = array_values($lines);
  
  foreach ($lines as $line_num =&gt; $dataset) {
      //output
  }
  </code></pre>