Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first non zero value and last non zero value indexes in array?

Tags:

php

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.

like image 323
SK2017 Avatar asked Dec 05 '22 12:12

SK2017


2 Answers

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
like image 164
Jigar Shah Avatar answered May 27 '23 09:05

Jigar Shah


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
)
like image 43
RomanPerekhrest Avatar answered May 27 '23 07:05

RomanPerekhrest