如何在数组中获得第一个非零值和最后一个非零值索引?

SK2*_*017 3 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
Run Code Online (Sandbox Code Playgroud)

是否有一个PHP函数可以获取第一个非零值索引最后一个非零值索引?还是一种非常漂亮的方式呢?

我知道我可以通过一些IF陈述来做到这一点,但它会变得非常混乱.

Jig*_*hah 9

你可以使用array_filter:

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

$result = array_filter($array); // it will filter false values 

echo key($result); // 6
end($result); // set pointer to end of the array
echo key($result); // 12
Run Code Online (Sandbox Code Playgroud)

工作演示