Jump to content

Calling the last string of an array


etrader

Recommended Posts

Example:

 

count = "0";
foreach ( $array as $value ) {
  // Do stuff with $value
count++;
}

$count1 = $count - '1';
//echo next before last array
echo $array['$count1;];

//echo last array
echo $array['$count;];

 

I didn't test this, but it should be close.

Link to comment
Share on other sites

sidenote...if you know that all you are ever going to want is the last one or two, then you can do as previous posters have shown. But if you want to be able to grab a variable amount, you will have to put those in a loop.  The better way to handle this is to do something like this:

 

// number of elements from the end you want
$n = 2;
// if you don't care about preserving array keys use this
$outputArray = array_slice($inputArray, -($n));
// if you care about preserving array keys, use this
$outputArray = array_slice($inputArray, -($n), count($inputArray), true);

 

Then you will have $outputArray as an array of the last element(s) in your original array.  You will be able to specify an arbitrary number with $n and just loop through $outputArray.

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.