title: finding the index of last occurrence of an element in an array using binary search PHP
body: <p>The array given has duplicate elements, So basically, I want to find the <code>index</code> of the last occurrence of the element I've searched. </p>
  
  <pre><code>$arr = array(2, 3, 4, 4, 5, 6, 4, 8);
  $x = 4; // number to search
  $low = 0;
  $high = count($arr)-1;
  // I want this function to return 6 which is the index of the last occurrence of 4, but instead I'm getting -1 .
  function binary_search_last_occ($arr, $x, $low, $high)
  {
      while ($low &lt;=$high)
      {
          $mid = floor(($low+$high)/2);
          $result = -1;
          if ($arr[$mid] == $x)
          {
              // we want to find last occurrence, so go for
              // elements on the right side of the mid 
              $result = $mid;
              $low = $mid+1;
          }
          else if($arr[$mid] &gt; $x)
          {
              $high = $mid-1;
          }
          else
              $low = $mid+1;
      } 
      return $result;  
  }
  echo binary_search_last_occ($arr, $x, $low, $high); // outputs -1 ? 
  </code></pre>
  
  <p>I'm not sure, why I'm getting -1. Any suggestions?</p>