Php array iterator get last element

    Table of contents
  • Find the last element of an array while using a foreach loop in PHP
  • Determine the first and last iteration in a foreach loop in PHP?
  • Determine the First and Last Iteration in a Foreach Loop in PHP
  • 5 Ways To Loop Through An Array In PHP

Find the last element of an array while using a foreach loop in PHP

for(int i=0; i< arr.length;i++){
     boolean isLastElem = i== (arr.length -1) ? true : false;        
}
$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
  if(++$i === $numItems) {
    echo "last index!";
  }
}    
$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 = 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";
}
foreach ($some_array as $element) {
    if(!next($some_array)) {
         // This is the last $element
    }
}
foreach($array as $value) {
    if ($value === reset($array)) {
        echo 'FIRST ELEMENT!';
    }

    if ($value === end($array)) {
        echo 'LAST ITEM!';
    }
}
$last_key = array_key_last($array);
foreach ($array as $key => $value) {
    if ($key == $last_key) {
        // last element
    } else {
        // not 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!';
}
$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;
}
foreach($array as $key=>$value) 
{ 
    echo $value;
    if($key != count($array)-1) { echo ", "; }
}
$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;
}
$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";
     }
}  
$data = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'];
$result = "";
foreach($data as $value) {
    $result .= (next($data)) ? "$value, " : $value;
}
print $result;
$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;
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;
    }
}
for ($i=0;$i<count(arr);$i++){
    $i == count(arr)-1 ? true : false;
}
end(arr);
arr[1];
end( $elements );
$endKey = key($elements);
foreach ($elements as $key => $value)
{
     if ($key == $endKey) // -- this is the last item
     {
          // do something
     }

     // more code
}
$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>";

}
foreach($items as $idx => $item) {
    if (!isset($items[$idx+1])) {
        print "I am last";
    }
}
$array  = array("dog", "rabbit", "horse", "rat", "cat");
foreach($array as $index => $animal) {
    if ($index === array_key_first($array))
        echo $animal; // output: dog

    if ($index === array_key_last($array))
        echo $animal; // output: cat
}
$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);
    }
}
   $rev_array = array_reverse($array);

   echo array_pop($rev_array);
<?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;
?>
$numItems = count($arr);
$i=0;
$firstitem=$arr[0];
$i++;
while($i<$numItems-1){
    $some_item=$arr[$i];
    $i++;
}
$last_item=$arr[$i];
$i++;
    $result = $where = "";
    foreach ($conditions as $col => $val) {
        $result = $where .= $this->getAdapter()->quoteInto($col.' = ?', $val);
        $where .=  " AND ";
    }
    return $this->delete($result);
$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;
}

Find the last element of an array while using a foreach loop in PHP

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

Determine the first and last iteration in a foreach loop in PHP?

1: First iteration 
6: Last iteration
1: First iteration 
6: :ast iteration
1: First iteration 
6: Last iteration

Determine the First and Last Iteration in a Foreach Loop in PHP

for($array as $key => $value){
    // Add code here
}
$array  = array("dog", "rabbit", "horse", "rat", "cat");
$x = 1;
$length = count($array);

foreach($array as $animal){
    if($x === 1){
        //first item
        echo $animal; // output: dog
    }else if($x === $length){
        echo $animal; // output: cat
    }
    $x++;
}
$array  = array("dog", "rabbit", "horse", "rat", "cat");
foreach($array as $index => $animal) {
    if ($index === array_key_first($array))
        echo $animal; // output: dog

    if ($index === array_key_last($array))
        echo $animal; // output: cat
}

5 Ways To Loop Through An Array In PHP

        $CodeWallTutorialArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread", "RedSauce"];
        $arrayLength = count($CodeWallTutorialArray);
        
        $i = 0;
        while ($i < $arrayLength)
        {
            echo $CodeWallTutorialArray[$i] ."<br />";
            $i++;
        }
Eggs
Bacon
HashBrowns
Beans
Bread
RedSauce
        $CodeWallTutorialArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread", "RedSauce"];

        for ($i = 0; $i < count($CodeWallTutorialArray); $i++)  {
            echo $CodeWallTutorialArray[$i] ."<br />";
        }
Eggs
Bacon
HashBrowns
Beans
Bread
RedSauce
       $foodArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread"];

        foreach ($foodArray as $food)  {
            echo $food ."<br />";
        }
Eggs
Bacon
HashBrowns
Beans
Bread
       $foodArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread"];
        $i = 0;
        
        do {
            echo $foodArray[$i] . "<br />";
            $i++;
        }
        while ($i < count($foodArray));
Eggs
Bacon
HashBrowns
Beans
Bread
        $programmingLanguagesArray = ["PHP", "C++", "C#", "Python", "Java"];
        
        $arrObject = new ArrayObject($programmingLanguagesArray);
        $arrayIterator = $arrObject->getIterator();

        while( $arrayIterator->valid() )
        {
            echo $arrayIterator->current() . "<br />";
            $arrayIterator->next();
        }
PHP
C++
C#
Python
Java

Next Lesson PHP Tutorial

How can we get the last element of an array in PHP?

You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.

How do you find the last element of an array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

How do I find the last iteration?

Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.

How can get first and last value in array in PHP?

One way of doing this is to use the array_values() function, which will return an array with all of the key values reset. This means that the first item in the array will have a key of 0 and the last item will have a key of the length of the array, minus 1.