Home > Net >  Range by using array of booleans
Range by using array of booleans

Time:07-12

hey guys I'm working a the range function for grades in the existing system that was already built, the grades are stored as an array of booleans so for example:

[true, true, true, true, true, true, false, false, false...]

grade number is element 1

I want to create a range function based on this array so, for example, this array the range is grade 1-6, any idea what is the most efficient way to do such thing, was thinking about running with loop and stoping the range when value is false, but maybe there is a better way.

CodePudding user response:

Looping is obviously the most simplest way. There is no more efficient way unless we get to know more strict constraints or any modifications being done while storing the data itself.

There sure is a one liner for this where you can get the size of the range. So, the range is obviously 1 - size. You can use array_search to get the index of the first element that is false and use this index the length/size of the range.

We use array_merge to deliberately add a dummy false value to make the function return the correct size in case of all truthy values.

Snippet:

<?php

echo array_search(false, array_merge($d, [false]));

Online Demo

CodePudding user response:

Usually array_count_values help to count duplicate values in array, but if you have boolean values then it wont work.But array_filter can help for this to count boolean values.Here is the example:

echo $true_count = count(array_filter(array_values($array)));
echo $false_count = count($input_array) - $true_count;

Hope this helps!

Thanks

  • Related