Php How to Determine the First and Last Iteration in a Foreach Loop

PHP How to determine the first and last iteration in a foreach loop?

You could use a counter:

$i = 0;
$len = count($array);
foreach ($array as $item) {
if ($i == 0) {
// first
} else if ($i == $len - 1) {
// last
}
// …
$i++;
}

How can I detect the first and the last element inside a foreach loop?

No need of foreach loop, just use a foreach loop and count. the foreach loop return an array.

$path = "monkey/cat/horse";

$arr = explode("/", $path);
$count = count($arr);


foreach($arr as $key => $value){
if($key == 0) echo "first:".$value;
elseif($key == ($count - 1)) echo "last:".$value;
}

Result

first:monkey
last:horse

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

It sounds like you want something like this:

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

That being said, you don't -have- to iterate over an "array" using foreach in php.

Php - Foreach returning one value, first or last

When you have a return the code would not execute further. Generate the whole data, then return that data.

You can either built an array. Like -

$urls= array();
foreach($matches[0] as $matchbun)
{
.....
$urls[]= ucfirst($url_final);
}
return $urls;

Or You can generate a string. Like -

$urls= '';
foreach($matches[0] as $matchbun)
{
.....
$urls.= ucfirst($url_final);
}
return $urls;

How do I know the last iteration of for loop?

if($i==$d-1){
//last iteration :)
}

foreach loop how to expect first result?

You can initialize a variable outside the foreach and count inside the iteration.

$count=0;
foreach($allposts as $posts)
{
$count++; // incrememnt

if($count==1)
{
// this is the first post
}
}

Option 2:
Use for loop instead of foreach

for($i=0; $i<=count($allposts); $i++)
{
if($i==0) // this is the first post.
echo $allposts[$i];
}

Using CSS to float your posts:

.post:nth-child(odd){
float: left;
}

.post:nth-child(even){
float: right;
}


Related Topics



Leave a reply



Submit