Jarla Jarla - 7 months ago 16
PHP Question

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

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

Answer

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