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
Query With Multiple Values in a Column
Update Data on a Page Without Refreshing
Sending Post Requests Without Waiting for Response
How to Prevent Mails Sent Through PHP Mail() from Going to Spam
Unable to Upload File Greater Than 2Mb in Laravel
How to Capitalize First Letter in Laravel Blade
How to Get Filename from a Variable (Url) in PHP
Get All Hrefs from String But Then Replace Via Another Method
How to Configure Xampp to Send Mail from Localhost
How to Get Newest Data With 'Created_At' Column
How to Do File Upload Using Jquery Serialization
Php Fatal Error: Uncaught Pdoexception: Could Not Find Driver
Laravel Print Array in Blade PHP
Disable the Button in the Table Based on the Td Text
How to Stop My PHP Form Resubmitting Input After Page Refresh