Ok So I have an PHP array of data like the following
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
Is there a PHP function that would grab the first Non-Zero Value index and the last Non-Zero value index? Or a very beautiful way to do it?
I know I can do this with a few IF
statements, but it will become very messy.
You can use array_filter:
Demo: Link
$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
Alternative solution with single array_reduce()
function:
$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);
The output:
Array
(
[0] => 6
[1] => 12
)
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