在php中使用循环时如何检查最后一个循环? [英] How to check for last loop when using for loop in php?

查看:138
本文介绍了在php中使用循环时如何检查最后一个循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在使用for循环php时检查最后一个循环?

这是我的代码,但是不行。

  $ x =10; ($ i = 0; $ i <$ x; $ i ++){
if $ $ $
echo $ $ i last ;
} else {
echo$ i last;
}
echo< br />;
}
?>

当我测试它的echo

<$ p $最后
1没有最后
2没有最后
3没有最后
4没有最后
5没有最后
6没有最后
7没有最后
8没有最后
9没有最后



<我怎样才能使代码检查最后一个循环?谢谢。

解决方案

PHP中还有其他数据类型比字符串。你正在做的是比较字符串,而不是实际数字。



$ x =10; will没有将 $ x 设置为 10 ,而是设为10,它是由一个零构成的字符串。这不一定是数值10。您的比较然后采用这个字符串,并使用表达式'$ x比较它与循环的计数器变量 - 1'。这是这里最重要的事情。 PHP不会替换单引号字符串中的变量。这是一个比较的例子:

  $ foo = 42; 
echo'$ foo Bar'; //输出:$ foo Bar
echo$ foo Bar; //输出:42

所以,基本上你的 if condition的作用是检查你的循环计数器是否不等于'$ x - 1'。比较字符串完全不同于比较数字,在这种情况下,它根本不是你想要的。 (特别是因为PHP的等式( == )和不等式运算符(!= )有时会出乎意料地出现, )



偶然的PHP试图尽可能地帮助你,这就是为什么你的代表循环工作。在那里你比较一个数字和一个字符串。这没有任何意义,但PHP使它为你工作。 ;)

只要使用所有的数字值而不用字符串表示法:

 <?php 
$ x = 10; $
($ i = 0; $ i <$ x; $ i ++)
{
if($ i!=($ x - 1)){
echo $我没有最后一个;
} else {
echo $ i。last;
}
echo< br>;
}


How to check for last loop when using a for loop php ?

This is my code, But it not work.

$x = "10";
for ($i = 0; $i < $x; $i++) {
    if ($i != '$x - 1') {
        echo "$i no last";
    } else {
        echo "$i last";
    }
    echo "<br/>";
}
?>

When I test it's echo

0 last
1 no last
2 no last
3 no last
4 no last
5 no last
6 no last
7 no last
8 no last
9 no last

How can I make the code check for the last loop? Thank you.

解决方案

There are other data types than strings in PHP. What you are doing is comparison of strings, not of actual numbers.

$x = "10"; will not set $x to 10, but to "10", which is the string built of a one and a zero. This has not necessarily the numerical value 10.

Your comparison then takes this string and compares it to the loop's counter variable using the expression '$x - 1'. This is the most significant thing here. PHP does not replace variables in single-quoted strings. Here is an example for comparison:

$foo = 42;
echo '$foo Bar'; // Output: $foo Bar
echo "$foo Bar"; // Output: 42 Bar

So, basically what your if condition does is to check if your loop's counter is not equal '$x - 1'. Comparing strings works completely differently than comparing numbers and in this case it does not at all what you intended anyway. (Especially because PHP's equality (==) and inequality operator (!=) sometimes behave really unexpectedly, if you're not familiar with types.)

Accidentally PHP tries to help you as much as it can, which is why your for loop works. In there you compare a number to a string. That makes not sense, but PHP makes it work for you. ;)

Just use everything as numerical values without the string notation:

<?php
$x = 10;
for($i=0; $i < $x; $i++)
{
    if($i != ($x - 1)) {
        echo $i."no last";
    } else {
        echo $i."last";
    }
    echo "<br>";
}

这篇关于在php中使用循环时如何检查最后一个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆