Search code examples
phpif-statementforeachcomparisoncomparison-operators

PHP string sort by letter range can't execute single character comparison


I'm working on outputing a list of companies in a foreach statement. To compare the first letters of each company I'm substinging the first character of each. These need to be sent through an if comparitor operation to see if it's the first occurance of each range of inital character. The var_dump shows that the srt_cmp has found the values intended. When I use the value in a if comparison for many combination, the if statement will not execute.

  <?php
  $stringCompanyListing = '<!-- beginning of business listing -->'."\n";
  $countCompanies=0;
  $haveStrungAD = "";
  $haveStrungEI = "";
  $haveStrungJO = "";
  $haveStrungPU = "";
  $haveStrungVZ = "";

  foreach ($files as $file){
    $company = new SimpleXMLElement($file, 0, true); 
    $COMPANYKEY[$countCompanies] = basename($file, '.xml');
  if ($countCompanies >= 1){
    $currentCompany = substr($COMPANYKEY[$countCompanies],0, 1);
    $previousCompany = substr(($COMPANYKEY[($countCompanies-1)]),0, 1);
  $checkForNavigation = strcmp($previousCompany, $currentCompany);
// var_dump at this point show intended values such as "A" and "-1"

  if ($haveStrungAD == ""){
    if ($currentCompany == range("A", "D")){
      if ($checkForNavigation <= -1){
        $stringCompanyListing .= '    <div class="categoryHeading"><a name="atod"></a>A-D</div>'; 
        $haveStrungAD = "done";
      }
        }
          }
  if ($haveStrungEI == ""){
    if ($currentCompany == range("E", "I")){
      if ($checkForNavigation <= -1){
        $stringCompanyListing .= '    <div class="categoryHeading"><a name="etoi"></a>E-I</div>'; 
        $haveStrungEI = "done";
      }
    }
  }
// more if comparisons omitted
}
$countCompanies++;
}

Solution

  • Since you have all the company names in an array ($COMPANYKEY), couldn't you just sort the array using either usort () or uasort() (depending on if you need the keys to remain attached to the values). Then loop through the array and assign companies to the appropriate array. For example,

    uasort($COMPANYKEY, function ($a, $b) {
    return $a < $b;
    });
    foreach ($COMPANYKEY AS $comp)
    {
    $char = substr($comp, 0, 1); //get first letter
    if ($char <= 'd')
        $atod[] = $comp;
    elseif ($char > 'd' && $char <= 'm')
        $etom[] = $comp;    
    }
    

    You can write additional conditions to load into the company into additional arrays, or you can use a switch statement on $char and write a bunch of cases. Either way, this should load each.

    Additionally, if you are using your code, you need to not use == operator and use the inarray() function. range returns an array of values, so you need to check if your value is that array, not is equal to an array.

    Hope this helps.