I want to detect the first and the last element inside a foreach loop:
$path = "monkey/cat/horse";
foreach(explode('/', $path) as $segment) {
echo $segment;
}
My desired result is:
first:monkey
last:horse
This is how I tried to solve it:
$path = "monkey/cat/horse";
$explode = explode('/', $path);
foreach($explode as $segment) {
if (current($explode) == $segment){
echo "first:".$segment;
} echo "<br>";
if (end($explode) == $segment){
echo "last:".$segment;
}
}
But my result is:
first:horse
last:horse
you can do a count(). or if you're looking for ONLY the last element, you can use end(). end(arr); returns only the last element.
This foreach is itself inside the main loop, and echoing out a div for each ID has access to. In the life cycle of the main array, this will happen 13 times. The reason you are seeing duplicates is because you have top-level array elements which contain the same IDs as other elements.
forEach() , and it will definitely iterate over array elements in ascending index order (skipping indices that were never assigned a value).
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
This works as fine.
$path = "monkey/cat/horse";
$explode = explode('/', $path);
echo "first:".current($explode);
echo "<br>";
echo "last:".end($explode);
WITH LOOP:
$path = "monkey/cat/horse";
$explode = explode('/', $path);
$cont = 0;
foreach($explode as $segment) {
if ($cont == 0){
echo "first:".$segment;
}
echo "<br>";
if ($cont > count($segment)){
echo "last:".$segment;
}
$cont = $cont +1;
}
Get length of the array.
Get a counter and increment it over foreach.
In the loop:
1) if counter is 0
, its first element.
2) If counter is array count minus one, its the last element.
<?php
$path = "monkey/cat/horse";
$explode = explode('/', $path);
$len = count($explode);
$i=0;
foreach($explode as $segment) {
if ($i == 0) {
echo "first: ".$segment;
echo "<br/>";
}
if ($i == ($len-1)) {
echo "last: ".$segment;
}
++$i;
}
?>
Output:
first: monkey
last: horse
Live demo
your code has only a little problem, try to change the current function by reset function. Like this:
$path = "monkey/cat/horse";
$explode = explode('/', $path);
foreach($explode as $segment) {
if (reset($explode) == $segment){
echo "first: $segment";
}
echo "<br>";
if (end($explode) == $segment){
echo "last: $segment";
}
}
Here you are the reference about "reset" function: http://php.net/manual/es/function.reset.php
Regards!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With