其他所有答案的效率都太低了,因为他们在内部 for() 循环中使用 str_split() 来构建数组。
每次都用逗号连接您的值并要求您编写一个单独的条件来处理逗号。这只会使您的代码混乱。最佳做法是将所有值存储在一个数组中,然后使用implode() 将它们与逗号粘合在一起——这样可以避免不需要的尾随逗号。 end() 是提取最后一个值的最佳方式。
这是一种更快的方法(因为它避免了不必要的循环和函数调用)来动态构建数组,将其转换为 csv 字符串,并访问数组中的最新元素:
代码:
$d="5"; // must be declared as string for strpos()
$x11=$d*11; // set only duplicate occurrence in range
for($x=1; $x<100; ++$x){
if(strpos($x,$d)!==false){ // if at least one $d is found
$array[]=$x;
if($x==$x11){ // if two $d are found in integer
$array[]=$x;
}
}
}
echo implode(',',$array),"<br>Last number: ",end($array); // display
输出:
5,15,25,35,45,50,51,52,53,54,55,55,56,57,58,59,65,75,85,95
Last number: 95
此方法进行 99 次迭代、99 次 strpos() 调用和 20 次比较以达到所需的结果。
将此与此页面上的所有其他代码进行比较,这些代码进行了 99 次外循环迭代、99 次 strlen() 调用、189 次内循环迭代、189 次 str_split() 调用和 189 次比较。
*faster 仍然是删除 strpos() 块内的比较,将 x11 值添加到循环外的数组中,然后在显示之前对数组进行排序。像这样:
代码:
$d="5"; // must be declared as string for strpos()
$array[]=$d*11; // store only duplicate occurrence in range
for($x=1; $x<100; ++$x){
if(strpos($x,$d)!==false){ // if at least one $d is found
$array[]=$x;
}
}
sort($array);
echo implode(',',$array),"<br>Last number: ",end($array); // display
这是使用函数迭代的替代方法:
代码:
$d=5;
$array=array_filter(range(1,99),function($v)use($d){return strpos($v,(string)$d)!==false;})+[$d*11];
sort($array); // zero-index the keys and position the appended value
echo implode(',',$array),"<br>Last number: ",end($array); // display
输出:
5,15,25,35,45,50,51,52,53,54,55,55,56,57,58,59,65,75,85,95
Last number: 95