TheWebs
TheWebs

Reputation: 12933

Do something before the end of the array

I have an array that would look something such as this:

$array = array('element1', 'element2', 'element3');

foreach($array as $a){
    echo $a;
}

what I need to do is do somehing before the last element of the array, so that my echo looks like this:

element1, element2, Look Ma! I did something!, element3.

what I want is to run a function if and only if we are JUST before the last element in the array, regardless of size.

I have thought of using end($array); but if so would I do?

foreach($array as $a){
    if(!end($array)){
        call_func(); // this seems wrong.
    }

    echo $a;
}

thoughts?

Upvotes: 1

Views: 66

Answers (5)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

try:

$last_key = end(array_keys($array));
foreach($array as $key => $a){
    if ($key == $last_key) {
        call_func(); 
    }

    echo $a;
}

OR you can also do,

$array = array('element1', 'element2', 'element3');
end($array);
$last_key = key($array);
foreach($array as $key => $a){
    if ($key == $last_key) {
        call_func(); 
    }

    echo $a;
}

Upvotes: 4

bozdoz
bozdoz

Reputation: 12890

your if statement should be if($a == end($array)), but even that won't necessarily mean it's the last value of the array (there could be duplicates).

Upvotes: 0

scottlimmer
scottlimmer

Reputation: 2278

Typically I would do something like:

$arrlen = count($array);
foreach($array as $i => $a) {
  if ($arrlen == $i + 1) {
    call_func();
  }
  echo $a;
}

Upvotes: 0

Suresh Kamrushi
Suresh Kamrushi

Reputation: 16086

You can do like this-

$array = array('element1', 'element2', 'element3');
$count = count($array)-1;
$loop = 1;
foreach($array as $a){
    echo $a;
    $loop++;
    if($count == $loop)
      echo "You text to be print";
}

Upvotes: 0

alex
alex

Reputation: 490637

You can check against the end() of your array.

$lastElement = $currentElement === end($array)

In your example, that'd be...

foreach($array as $a){
    if($a === end($array)){
        // Last iteration.
    }

    echo $a;
}

This of course relies on elements being unique. Otherwise, you could use a counter, or use the key and compare that to the last key (end(array_keys($array))).

Upvotes: 1

Related Questions