IT story

PHP에서 foreach 루프를 사용하는 동안 배열의 마지막 요소 찾기

hot-time 2020. 5. 10. 10:27
반응형

PHP에서 foreach 루프를 사용하는 동안 배열의 마지막 요소 찾기


일부 매개 변수를 사용하여 SQL 쿼리 작성자를 작성 중입니다. Java에서는 배열 길이로 현재 배열 위치를 확인하면 for 루프 내부에서 배열의 마지막 요소를 매우 쉽게 감지 할 수 있습니다.

for(int i=0; i< arr.length;i++){
     boolean isLastElem = i== (arr.length -1) ? true : false;        
}

PHP에서는 배열에 액세스하기 위해 정수가 아닌 인덱스를 가지고 있습니다. 따라서 foreach 루프를 사용하여 배열을 반복해야합니다. 이것은 어떤 결정을 내려야 할 때 문제가됩니다 (제 경우에는 쿼리를 작성하는 동안 추가 또는 매개 변수).

이 작업을 수행하는 표준 방법이 있어야합니다.

PHP에서 어떻게 해결합니까?


다음과 같이 원하는 것처럼 들립니다.

$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
  if(++$i === $numItems) {
    echo "last index!";
  }
}    

즉, foreachPHP에서 사용하는 "배열"을 반복하지는 않습니다 .


배열의 마지막 키 값을 사용 end(array_keys($array))하여 현재 키와 비교할 수 있습니다.

$last_key = end(array_keys($array));
foreach ($array as $key => $value) {
    if ($key == $last_key) {
        // last element
    } else {
        // not last element
    }
}

왜 그렇게 복잡한가?

foreach($input as $key => $value) {
    $ret .= "$value";
    if (next($input)==true) $ret .= ",";
}

마지막 값을 제외한 모든 값 뒤에을 추가합니다!


toEnd가 0에 도달하면 루프의 마지막 반복에 있음을 의미합니다.

$toEnd = count($arr);
foreach($arr as $key=>$value) {
  if (0 === --$toEnd) {
    echo "last index! $value";
  }
}

마지막 값은 루프 후에도 계속 사용할 수 있으므로 루프 후에 더 많은 것을 위해 사용하려는 경우 더 좋습니다.

foreach($arr as $key=>$value) {
  //something
}
echo "last index! $key => $value";

마지막 값을 특수 내부 루프로 취급하지 않으려는 경우. 배열이 큰 경우 더 빠릅니다. 동일한 범위 내에서 루프 후 배열을 재사용하는 경우 먼저 배열을 "복사"해야합니다.

//If you use this in a large global code without namespaces or functions then you can copy the array like this:
//$array = $originalArrayName; //uncomment to copy an array you may use after this loop

//end($array); $lastKey = key($array); //uncomment if you use the keys
$lastValue = array_pop($array);

//do something special with the last value here before you process all the others?
echo "Last is $lastValue", "\n";

foreach ($array as $key => $value) {
    //do something with all values before the last value
    echo "All except last value: $value", "\n";
}

//do something special with the last value here after you process all the others?
echo "Last is $lastValue", "\n";

그리고 원래 질문에 대답하기 위해 "제 경우에는 쿼리를 작성하는 동안 매개 변수를 추가하거나 추가 할 수 있습니다"; 이것은 모든 값을 반복 한 다음 첫 번째 값 이전 또는 마지막 값 이후가 아닌 "와"를 사용하여 문자열로 결합합니다.

$params = [];
foreach ($array as $value) {
    $params[] = doSomething($value);
}
$parameters = implode(" and ", $params);

이미 많은 답변이 있지만 특히 표준 방법으로 요청 된 경우 반복자를 살펴볼 가치가 있습니다.

$arr = range(1, 3);

$it = new CachingIterator(new ArrayIterator($arr));
foreach($it as $key => $value)
{
  if (!$it->hasNext()) echo 'Last:';
  echo $value, "\n";
}

다른 경우에도 더 유연하게 작동하는 것을 찾을 수 있습니다.


한 가지 방법은 반복자가 가지고 있는지 감지하는 것 next입니다. 반복자에 다음에 연결되지 않은 경우 마지막 루프 상태임을 의미합니다.

foreach ($some_array as $element) {
    if(!next($some_array)) {
         // This is the last $element
    }
}

따라서 배열에 고유 한 배열 값이 있으면 마지막 반복을 결정하는 것이 쉽지 않습니다.

foreach($array as $element) {
    if ($element === end($array))
        echo 'LAST ELEMENT!';
}

보시다시피, 마지막 요소가 배열에 한 번만 나타나는 경우 작동합니다. 그렇지 않으면 잘못된 경보가 발생합니다. 그것은 당신이 키를 비교할 필요는 없습니다 (확실히 고유합니다).

foreach($array as $key => $element) {
    end($array);
    if ($key === key($array))
        echo 'LAST ELEMENT!';
}

또한 엄격한 coparision 연산자를 참고하십시오.이 경우에는 매우 중요합니다.


배열이 변수에 저장되어 있다고 가정하면 ...

foreach($array as $key=>$value) 
{ 
    echo $value;
    if($key != count($array)-1) { echo ", "; }
}

첫 번째 또는 마지막을 제외한 모든 요소에 대해 무언가를 수행해야하고 배열에 하나 이상의 요소가있는 경우에만 다음 솔루션을 선호합니다.

나는 위의 많은 솔루션이 있고 내 전에 몇 달 / 1 년 게시했다고 알고 있지만, 이것은 그 자체로 상당히 우아하다고 느낍니다. 모든 루프 검사는 숫자 "i = (count-1)"검사와 달리 부울 검사이므로 오버 헤드를 줄일 수 있습니다.

루프의 구조는 어색 할 수 있지만 HTML 테이블 태그에서 thead (시작), tfoot (끝), tbody (현재)의 순서와 비교할 수 있습니다.

$first = true;
foreach($array as $key => $value) {
    if ($first) {
        $first = false;
        // Do what you want to do before the first element
        echo "List of key, value pairs:\n";
    } else {
        // Do what you want to do at the end of every element
        // except the last, assuming the list has more than one element
        echo "\n";
    }
    // Do what you want to do for the current element
    echo $key . ' => ' . $value;
}

예를 들어, 웹 개발 용어 에서 정렬되지 않은 목록 (ul) 의 마지막 요소를 제외한 모든 요소에 테두리 아래쪽을 추가하려면 대신 첫 번째 요소 (CSS : IE7 +에서 지원되는 첫 번째 자식 및 Firefox / Webkit은이 논리를 지원하지만 : last-child는 IE7에서 지원되지 않습니다).

중첩 루프마다 $ first 변수를 자유롭게 재사용 할 수 있으며 첫 번째 반복의 첫 번째 프로세스 중에 모든 루프가 $ first를 거짓으로 만들기 때문에 문제가 발생하지 않습니다. 따라서 중단 / 예외로 인해 문제가 발생하지 않습니다. .

$first = true;
foreach($array as $key => $subArray) {
    if ($first) {
        $string = "List of key => value array pairs:\n";
        $first = false;
    } else {
        echo "\n";
    }

    $string .= $key . '=>(';
    $first = true;
    foreach($subArray as $key => $value) {
        if ($first) {
            $first = false;
        } else {
            $string .= ', ';
        }
        $string .= $key . '=>' . $value;
    }
    $string .= ')';
}
echo $string;

출력 예 :

List of key => value array pairs:
key1=>(v1_key1=>v1_val1, v1_key2=>v1_val2)
key2=>(v2_key1=>v2_val1, v2_key2=>v2_val2, v2_key3=>v2_val3)
key3=>(v3_key1=>v3_val1)

이것이 마지막 요소를 찾는 쉬운 방법이어야합니다.

foreach ( $array as $key => $a ) {
    if ( end( array_keys( $array ) ) == $key ) {
        echo "Last element";
     } else {
        echo "Just another element";
     }
}  

참조 : 링크


이 방법을 연관 배열과 함께 계속 사용할 수 있습니다.

$keys = array_keys($array);
for ($i = 0, $l = count($array); $i < $l; ++$i) {
    $key = $array[$i];
    $value = $array[$key];
    $isLastItem = ($i == ($l - 1));
    // do stuff
}

// or this way...

$i = 0;
$l = count($array);
foreach ($array as $key => $value) {
    $isLastItem = ($i == ($l - 1));
    // do stuff
    ++$i;
}

나는이 "XY 문제"의 근원에서 OP가 단지 implode()기능 하기를 원한다는 강한 느낌을 가지고있다 .


EOF 어레이를 찾으려는 의도는 접착제뿐입니다. 아래 전술을 소개하십시오. EOF가 필요하지 않습니다.

$given_array = array('column1'=>'value1',
                     'column2'=>'value2',
                     'column3'=>'value3');

$glue = '';
foreach($given_array as $column_name=>$value){
    $where .= " $glue $column_name = $value"; //appending the glue
    $glue   = 'AND';
}
echo $where;

o / p :

column1 = value1 AND column2 = value2 AND column3 = value3

다음과 같이 원하는 것처럼 들립니다.

$array = array(
    'First',
    'Second',
    'Third',
    'Last'
);

foreach($array as $key => $value)
{
    if(end($array) === $value)
    {
       echo "last index!" . $value;
    }
}

count ()를 할 수 있습니다.

for ($i=0;$i<count(arr);$i++){
    $i == count(arr)-1 ? true : false;
}

또는 마지막 요소 만 찾고 있다면 end ()를 사용할 수 있습니다.

end(arr);

마지막 요소 만 반환합니다.

그리고 결과적으로 PHP 배열을 정수로 색인 할 수 있습니다. 그것은 완벽하게 행복합니다

arr[1];

"종료"를 사용하는 방법 http://php.net/manual/en/function.end.php


다음과 같이 할 수도 있습니다 :

end( $elements );
$endKey = key($elements);
foreach ($elements as $key => $value)
{
     if ($key == $endKey) // -- this is the last item
     {
          // do something
     }

     // more code
}

I kinda like the following as I feel it is fairly neat. Let's assume we're creating a string with separators between all the elements: e.g. a,b,c

$first = true;
foreach ( $items as $item ) {
    $str = ($first)?$first=false:", ".$item;
}

foreach ($array as $key => $value) {

  $class = ( $key !== count( $array ) -1 ) ? " class='not-last'" : " class='last'";

  echo "<div{$class}>";
  echo "$value['the_title']";
  echo "</div>";

}

Reference


Don't add a comma after the last value:

The array:

$data = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'];

The function:

$result = "";
foreach($data as $value) {
    $resut .= (next($data)) ? "$value, " : $value;
}

The result:

print $result;

lorem, ipsum, dolor, sit, amet


Here's another way you could do it:

$arr = range(1, 10);

$end = end($arr);
reset($arr);

while( list($k, $v) = each($arr) )
{
    if( $n == $end )
    {
        echo 'last!';
    }
    else
    {
        echo sprintf('%s ', $v);
    }
}

If I understand you, then all you need is to reverse the array and get the last element by a pop command:

   $rev_array = array_reverse($array);

   echo array_pop($rev_array);

You could also try this to make your query... shown here with INSERT

<?php
 $week=array('one'=>'monday','two'=>'tuesday','three'=>'wednesday','four'=>'thursday','five'=>'friday','six'=>'saturday','seven'=>'sunday');
 $keys = array_keys($week);
 $string = "INSERT INTO my_table ('";
 $string .= implode("','", $keys);
 $string .= "') VALUES ('";
 $string .= implode("','", $week);
 $string .= "');";
 echo $string;
?>

For SQL query generating scripts, or anything that does a different action for the first or last elements, it is much faster (almost twice as fast) to avoid using unneccessary variable checks.

The current accepted solution uses a loop and a check within the loop that will be made every_single_iteration, the correct (fast) way to do this is the following :

$numItems = count($arr);
$i=0;
$firstitem=$arr[0];
$i++;
while($i<$numItems-1){
    $some_item=$arr[$i];
    $i++;
}
$last_item=$arr[$i];
$i++;

A little homemade benchmark showed the following:

test1: 100000 runs of model morg

time: 1869.3430423737 milliseconds

test2: 100000 runs of model if last

time: 3235.6359958649 milliseconds


Another way to go is to remember the previous loop cycle result and use that as the end result:

    $result = $where = "";
    foreach ($conditions as $col => $val) {
        $result = $where .= $this->getAdapter()->quoteInto($col.' = ?', $val);
        $where .=  " AND ";
    }
    return $this->delete($result);

I personally use this kind of construction which enable an easy use with html < ul > and < li > elements : simply change the equality for an other property...

The array cannot contains false items but all the others items which are cast into the false boolean.

$table = array( 'a' , 'b', 'c');
$it = reset($table);
while( $it !== false ) {
    echo 'all loops';echo $it;
    $nextIt = next($table);
    if ($nextIt === false || $nextIt === $it) {
            echo 'last loop or two identical items';
    }
    $it = $nextIt;
}

You can dirctly get last index by:

$numItems = count($arr);

echo $arr[$numItems-1];


<?php foreach($have_comments as $key => $page_comment): ?>
    <?php echo $page_comment;?>
    <?php if($key+1<count($have_comments)): ?> 
        <?php echo ', '; ?>
    <?php endif;?>
<?php endforeach;?>

Here's my solution: Simply get the count of your array, minus 1 (since they start in 0).

$lastkey = count($array) - 1;
foreach($array as $k=>$a){
    if($k==$lastkey){
        /*do something*/
    }
}

Try this simple solution

$test = ['a' => 1, 'b' => 2, 'c' => 3];

$last_array_value = end($test);

foreach ($test as $key => $value) {
   if ($value === $last_array_value) {
      echo $value; // display the last value  
   } else {
     echo $value; // display the values that are not last elements 
   }
}

참고URL : https://stackoverflow.com/questions/665135/find-the-last-element-of-an-array-while-using-a-foreach-loop-in-php

반응형