Ver Mensaje Individual
  #18 (permalink)  
Antiguo 04/05/2014, 12:04
Avatar de Italico76
Italico76
 
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 17 años, 1 mes
Puntos: 292
Respuesta: Reemplazar última coma por " y"

El post anterior se hizo largo (mucho codigo)..... voy a postear la solucion "justa" donde podras ver que si cambias el orden, el resultado cambia poco (porque de todas formas hay repeticion de valores)

Código PHP:
Ver original
  1. <?php
  2. function italico1(&$arr)
  3.     {
  4.         $cant = count($arr);    
  5.    
  6.         if ($cant==0)  return null;        
  7.         $salida = null;
  8.        
  9.         if ($cant>1)
  10.         {
  11.             for ($i=0;$i<$cant-2;$i++)
  12.                 $salida .= $arr[$i].' ,';
  13.        
  14.             return $salida.$arr[$cant-2].' y '.$arr[$cant-1];  
  15.            
  16.         }else
  17.             return $arr[0];      
  18.    
  19.     }
  20.  
  21. function italico2(&$arr)
  22. {
  23.     switch (count($arr))
  24.     {
  25.     case 0: return null;
  26.     case 1: return $arr[0];
  27.     default:    
  28.         $ult = array_pop($arr);
  29.         return implode (' ,',$arr).' y '.$ult;
  30.     }    
  31. }
  32.  
  33. function alexis($array) {
  34.     $string = implode(", ", $array);
  35.     return substr_replace ($string, " y ", strrpos($string, ","), 2);
  36. }
  37.  
  38. $a[] = range(1, 1000,2);
  39. $a[] = range(1, 1500,3);
  40. $a[] = range(1, 3500,7);
  41.  
  42. $ini1 = microtime(true) * 1000;
  43. for ($i = 0; $i < 1000; $i++)
  44.     italico1($a[0]);
  45. $fin1 = microtime(true) * 1000;
  46. $tiempoItalico1 = $fin1 - $ini1;
  47.  
  48. $ini1 = microtime(true) * 1000;
  49. for ($i = 0; $i < 1000; $i++)
  50.     italico2($a[2]);
  51. $fin1 = microtime(true) * 1000;
  52. $tiempoItalico2 = $fin1 - $ini1;
  53.  
  54. $ini2 = microtime(true) * 1000;
  55. for ($i = 0; $i < 1000; $i++)
  56.     alexis($a[1]);
  57. $fin2 = microtime(true) * 1000;
  58. $tiempoAlexis = $fin2 - $ini2;
  59.  
  60.  
  61.  
  62.  
  63. echo "Italico (script #1): " . $tiempoItalico1."\n";
  64. echo "Italico (script #2): " . $tiempoItalico2."\n";
  65. echo "Alexis: " . $tiempoAlexis;

En el orden que quieras.....

Cita:
Alexis: 55 seg aprox
Italico #1: 162 seg aprox
Italico #2: 25 seg aprox << winner
Asi que... es cierto que se puede ganar velocidad con funciones nativas y de hecho las he utilizado en la ultima version pero a difierencia tuya no recorro el arreglo varias veces con distintas funciones (nativas o no) y por eso a la final.......... gano :)
__________________
Salu2!