the last iteration in a while loop

送分小仙女□ 提交于 2019-12-10 12:18:46

问题


I'm trying to get the last item in an array, when being iterated to output something different to a string.

if (count($this->condition) > 1) {
        $i=0;
        while ($i < count($this->condition)){
            if ($i == (count($this->condition) -1)) {

                foreach ($this->condition as $key => $value){

                    $query .= $value['columns']." = ".$value['value'];
                }
            } else {
                foreach ($this->condition as $key => $value){

                    $query .= $value['columns']." = ".$value['value']." AND ";
                    $i++;

                }
            }
        }
    } else {
        foreach ($this->condition as $key => $value){
            $query .= $value['columns']." = ".$value['value'];

        }
    }

However, it keeps adding the AND, meaning that $i == (count($this->condition)) is never true.

How do I resolve this?


回答1:


By far simpler method is to build an array of conditions, then implode them at the end.

$conditions = array();
foreach($this->condition as $key => $value) {
   $conditions[] = $values['columns'] . ' = ' . $value['value'];
}
$query = implode(' and ', $conditions);



回答2:


Arrays in PHP are zero-based. If count() returns n, then the last element in your array can be accessed at the n-1th index.

Hence:

if ($i == (count($this->condition)))

should be

if ($i == (count($this->condition) - 1))

Also, you are incrementing $i too often. $i++ should be moved outside the foreach loop. It should be like this:

while ($i < count($this->condition)) {
    if ($i == (count($this->condition) -1)) {
        foreach ($this->condition as $key => $value){
            $query .= $value['columns']." = ".$value['value'];
        }
    } else {
        foreach ($this->condition as $key => $value){
            $query .= $value['columns']." = ".$value['value']." AND ";
        }

        $i++;
    }
}



回答3:


The simple way: your if should be

 if ($i == count($this->condition)-1) {

as arrays are 0-indexed.

The even simpler way, though - as your code runs out of the while, $i will still be set. Why don't you read it after the while is done, and substract one?




回答4:


I've fixed it.

 if (count($this->condition) > 1) {
            $i=0;
            foreach ($this->condition as $key => $value){

                if ($i == ($conditionCount -1)) {
                    $query .= $value['columns']." = ".$value['value'];
                } else {
                    $query .= $value['columns']." = ".$value['value']." AND ";
                }
            $i++;
            }
    } else {
        foreach ($this->condition as $key => $value){
            $query .= $value['columns']." = ".$value['value'];

        }
    }


来源:https://stackoverflow.com/questions/13436414/the-last-iteration-in-a-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!