hello,

while iterating over an array i would like to check if I am currently on the last element. Until now I do the following, but I know that it will tragically decrease performance if the array is too big:

foreach ($aPropertiesForBinding as $sCurrentKey => $sCurrentValue) {

// do something

if ($sCurrentKey !== end(array_keys($aPropertiesForBinding))) {
	$sSql .= ', ';
}	
}		

has anyboda a better idea?

thx
Sebastian

    use the [man]count/man function to count the elements in the array. Then increment some number to keep track:

    <?php
    $max = count($aPropertiesForBinding)-1;
    $i=0;
    foreach($aPropertiesForBinding as $sCurrentKey => $sCurrentValue){
      // do something
      if($i<$max)
      {
        $sSql .= ', ';
      }
      else
      {
        // Last iteration
      }
      $i++;
    }

    Of course, if you're just building a query, and you know that you're going to have ", " after each element, just use substr to remove it:

    foreach($aPropertiesForBinding as $sCurrentKey => $sCurrentValue){
      // do something
      $sSql .= ', ';
    }
    $sSql = substr($sSql, 0, -2);

    EDIT:
    Forgot the increment....

      Moving the array_keys statements outside of the foreach loop should make it at least a bit faster. As long as you are not adding elements to the array within the loop it should work

      $final_key = end(array_keys($aPropertiesForBinding));
      
      foreach ($aPropertiesForBinding as $sCurrentKey => $sCurrentValue) {
      
      // do something
      
      if ($sCurrentKey !== $final_key) {
          $sSql .= ', ';
      }    
      } 
      

        yeah, I already thought about fetching the keys outside the array. I think I will do it that way. I thought there might be a better solution. Annotation to the first reply: please also think, that it should also work on associative arrays.

        thx
        Sebastian

          bpat's solution would work on associative arrays, but there is a step missing: you have to increment $i inside of that loop

            Either of my solutions would work on associative arrays. An associative array is no different than a regular array. The numerical keys are still there. But using the substr method i think might be faster than anything else since it doesn't matter what itteration it's on, and you're only cutting the string by two characters.

            Either way, you've got three options to go about it. All will work, which you go for is up to you.

              Write a Reply...