Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何获取数组中的第一个非零值索引和最后一个非零值索引?_Php - Fatal编程技术网

Php 如何获取数组中的第一个非零值索引和最后一个非零值索引?

Php 如何获取数组中的第一个非零值索引和最后一个非零值索引?,php,Php,我有一个PHP数据数组,如下所示 0 0 0 0 0 0 500 // Get index of this value which is 6 11000 100 110 221 1245 2141// Get index of this value which is 12 0 0 0 0 0 是否有一个PHP函数可以获取第一个非零值索引和最后一个非零值索引?还是一个非常漂亮的方法 我知道我可以用一些IF语句来实现这一点,但它会变得非常混乱。您可以使用: 演示: 您可以使用,然后使用reset(

我有一个PHP数据数组,如下所示

0
0
0
0
0
0
500 // Get index of this value which is 6
11000
100
110
221
1245
2141// Get index of this value which is 12
0
0
0
0
0
是否有一个PHP函数可以获取第一个非零值索引和最后一个非零值索引?还是一个非常漂亮的方法

我知道我可以用一些
IF
语句来实现这一点,但它会变得非常混乱。

您可以使用:

演示

您可以使用,然后使用
reset()
end()

如果未提供回调,则将删除所有等于FALSE的数组项(请参见转换为布尔值)


array\u filter()
默认情况下删除
0
false
'

使用单个
array\u reduce()函数的替代解决方案:

$arr = [0,0,0,0,0,0,500 ,11000,100,110,221,1245,2141,0,0,0,0,0];

$result = array_reduce($arr, function($r, $v) use (&$c){
    if ($v) $r[($r? 1:0)] = $c;
    $c++;
    return $r;
}, []);

print_r($result);
输出:

Array
(
    [0] => 6
    [1] => 12
)

值500的指数不应该是6吗?@lloiacono是的:P谢谢你指出学生的错误谢谢你的回答!
$arr = [0,0,0,0,0,0,500 ,11000,100,110,221,1245,2141,0,0,0,0,0];

$result = array_reduce($arr, function($r, $v) use (&$c){
    if ($v) $r[($r? 1:0)] = $c;
    $c++;
    return $r;
}, []);

print_r($result);
Array
(
    [0] => 6
    [1] => 12
)