我想检测foreach循环中的第一个和最后一个元素:
$path = "monkey/cat/horse";
foreach(explode('/', $path) as $segment) {
echo $segment;
}
我想要的结果是:
first:monkey
last:horse
这就是我试图解决的问题:
$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;
}
}
但我的结果是:
first:horse
last:horse
答案 0 :(得分:6)
不需要foreach循环,只需使用foreach
循环和count
。 foreach循环返回一个数组。
$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;
}
<强>结果强>
first:monkey
last:horse
答案 1 :(得分:3)
这很好。
$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;
}
答案 2 :(得分:1)
获取数组的长度。
获取一个计数器并将其增加到foreach上。
在循环中:
1)如果counter是0
,它的第一个元素。
2)如果计数器是数组减去1,则它是最后一个元素。
<?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;
}
?>
输出:
first: monkey
last: horse
答案 3 :(得分:1)
您的代码只有一点问题,尝试通过重置功能更改当前功能。像这样:
$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";
}
}
这里是关于“重置”功能的参考: http://php.net/manual/es/function.reset.php
问候!
答案 4 :(得分:0)
试试这个
<?php
$path = "monkey/cat/horse";
$arr = explode("/", $path);
$data= $arr;
echo end($data); //last value
echo reset($data); //firast value
?>