Jump to content

run code when a loop gets the last item of an array


Darkmatter5

Recommended Posts

How can I run a specific variation of some code only when a while loop gets to the last item of an array?  I have an example below of what I'm looking for.

 

The array is $list and contains the following items "1,2,3,4"

 

Now how can I have a loop statement that runs this code on all items, but when it's on the last item will run another code.

 

foreach($list as $lst) {

  echo "$lst[0], "; <- this is run on all elements except the last element

  if($list is on last element) { echo "$lst[lastelement]"; }

}

Link to comment
Share on other sites

Cool, but ummm can you explain the code?  What does the "$k => $lst" do?  Is it getting the number of elements and putting that into $k?  Then what does the "?" and ":" do?  Is the ":" for a range between $lst[0] and the last element?  Do I literally use $lst[lastelement]?

 

Thanks!

Link to comment
Share on other sites

Try something like this:

<?php
$list = range(1,rand(20,99));  // set up -- get some numbers in an array
shuffle($list);                       // set up -- randomize the array
$last_element = $list[count($list) - 1];
foreach ($list as $v)
    if ($v != $last_element)
          echo "last element not reached: $v <br>";
    else
          echo "last element reached: $v ... $last_element<br>";
?>

 

Ken

Link to comment
Share on other sites

or

<?php
$list = array(1,2,3,4,5);
$last_element = array_pop($list);
foreach ($list as $element) {
echo "$element isn't last.<br />\n";
}
echo "$last_element is last.<br />\n";
?>

 

 

That will not do an alternative if its last item which was what was desired I  think.

 

Actually it will, and it's fairly quick, especially for large data sets, because it removes per-iteration comparisons.

Link to comment
Share on other sites

My statement was lets say you have 5 items it will do

 

1

2

3

4

5

 

Special

 

Instead of

1

2

3

4

Special

 

Don't know which one was asked for

 

Make sense?

 

Yeah, they're certainly different, but the original post had this next to what you describe as the 1..2..3..4..5 -- "this is run on all elements except the last element"

 

So I assumed he wanted a completely different action for the last action instead of a supplemental one. That comment did contrast some with his initial request, so who knows what he truly wants but him? :D

Link to comment
Share on other sites

I'm just feeling like coding something fancy tonight

 

$arr = range(1,4);  //create array of numbers 1,2,3,4
for ($i=1;$i<count($arr);$i++)
{
  // code for all but last elements
}
//code for last element

 

Not tested. Look crappy... But adds to variation :P

Link to comment
Share on other sites

<?php
echo 'Code 1:<br />';
$list = array(1,2,3,4);
echo implode(', ', $list);
echo "<hr />\n";

echo 'Code 2:<br />';
$list = array(1,2,3,4);
$pre = '';
foreach ($list as $item){
echo $pre, $item;
$pre = ', ';
}
echo "<hr />\n";

echo 'Code 3:<br />';
$list = array(1,2,3,4);
$last = array_pop($list);
foreach ($list as $item){
echo $item, ', ';
}
echo $last;
echo "<hr />\n";

echo 'Code 4:<br />';
$list = array(1,2,3,4);
$i = 0;
while (isset($list[$i +1])){
echo $list[$i++], ', ';
}
echo $list[$i];
echo "<hr />\n";
//etc.
?>

 

 

Link to comment
Share on other sites

  • 2 years later...

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

 

And it's thus quite clear that the check costs a lot, and of course it gets even worse the more variable checks you add ;)

Link to comment
Share on other sites

While I totally respect your authority and your forum, this thread is still one of the main google hits on the subject, and should thus be complete in my humble opinion.

 

(I know I'm a mod too and I hate necro .. but this issue is as valid today as it was 2.5 years ago)

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.