How to get a percentage of an array?

I am wondering how to get a certain percentage of an array.

Say:

$array = array ("I","am","not","a","professional","coder","so","please","help","me"); 

It consists of ten meanings.

I would like to write a method to get a fragment of it.

 public function get_percentage($percentage) {...;return $array_sliced;} 

So, if I need an array containing only "I", I would use

 $this->get_percentage(10) //10 stands for 10% //returns $slice = array ("I"); 

It would also be great if $ num could be rounded to the nearest usable value. For instance:.

 $this->get_percentage(8) //8 stands for 8% but the function will treat this as 10% //returns $slice = array ("I"); 

I did not find a similar question here, I hope that this is not too difficult.

+4
source share
1 answer

This method, using array_slice() , should do the trick for you:

 public function get_percentage($percentage) { $count = count($this->arr) * ($percentage / 100); return array_slice($this->arr, 0, round($count)); } 
+11
source

Source: https://habr.com/ru/post/1391160/


All Articles