PHP代码:
$b = 1;
$ab = 100;
for ($b; $b < $ab; $b++)
{
$len = strlen($b);
$c = 0;
for ($c; $c < $len; $c++)
{
$split = str_split($b);
if ($split[$c] == 5)
{
echo $b . ',';
}
}
}
结果是:
5,15,25,35,45,50,51,52,53,54,55,55,56,57,58,59,65,75,85,95,
但我想删除最后一个逗号并获取最后一个值。
答案 0 :(得分:6)
已完成更改。
1。定义$result=array();
;
2。数组$result[]= $b;
3。以,
$result= implode(",", $result);
隐藏数组
<?php
$b = 1;
$ab = 100;
$result=array();
for ($b; $b < $ab; $b++)
{
$len = strlen($b);
$c = 0;
for ($c; $c < $len; $c++)
{
$split = str_split($b);
if ($split[$c] == 5)
{
$result[]= $b;
}
}
}
$lastElement =end($result);//last element
$result= implode(",", $result);
print_r($result);
答案 1 :(得分:1)
有两种方法。您可以使用数组中的所有值,也可以将字符串转换为数组 第一种方式是
$b = 1;
$ab = 100;
$arr=[];
for($b; $b < $ab; $b++){
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
$arr[]=$b;//push value into the array
}
}
}
echo implode(",",$arr);//create string from array
echo end($arr);// return the last value of a array
第二种方式是
$b = 1;
$ab = 100;
$str="";
for($b; $b < $ab; $b++){
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
$str .=$b .','; //create a string with name str
}
}
}
$str=rtrim($str,','); //remove last comma of this string
echo $str;
$arr=explode(",",$str);//convert string to array
echo end($arr);//return the last value of this array
答案 2 :(得分:0)
使用rtrim然后爆炸来获取数组。
$b = 1;
$ab = 100;
for($b; $b < $ab; $b++){
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
echo $b .',';
}
}
}
$b = rtrim(',',$b);
$b = explode(',',$b);
$b = $b[count($b)-1];
答案 3 :(得分:0)
这将删除最后一个昏迷,并为您提供最后一个值(作为字符串)。您始终可以将字符串更改回整数。
$b = 1;
$ab = 100;
$string = "";
for($b; $b < $ab; $b++){
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
$string .= $b .',';
}
}
}
$string = trim($string,",");
$pos = strripos($string,",");
echo substr($string,$pos + 1);
答案 4 :(得分:0)
只需定义最后一个变量:
$b = 1;
$ab = 100;
$last = 0;
for($b; $b < $ab; $b++){
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
if($last > 0){
echo ',';
}
echo $b;
$last = $b;
}
}
}
每次都在$last
。
对于昏迷,它会检查$last > 0
是否$b
答案 5 :(得分:0)
您也可以使用这些代码。测试它并且它有效。
$b = 1;
$ab = 100;
$hasValue = false;
for($b; $b < $ab; $b++){
$hasFive = false;
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
$hasFive = true;
}
}
if (!$hasValue && $hasFive) {
echo $b;
$hasValue = true;
}else if($hasFive){
echo ','.$b;
}
}
答案 6 :(得分:0)
$b = 1;
$ab = 100;
$hasValue = false;
for($b; $b < $ab; $b++){
$hasFive = false;
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
$hasFive = true;
}
}
if (!$hasValue && $hasFive) {
echo $b;
$hasValue = true;
}else if($hasFive){
echo ','.$b;
}
}