I'm wondering how to get a determined percentage of an array.
Let's say:
$array = array ("I","am","not","a","professional","coder","so","please","help","me");
It's composed of ten values.
I'd like to write a method to get a slice of it.
public function get_percentage($percentage) {...;return $array_sliced;}
So if I want an array containing only "I", I'd use
$this->get_percentage(10) //10 stands for 10%
//returns $slice = array ("I");
Also, it would be great if the $num could be rounded to the nearest useful value. E.g.:
$this->get_percentage(8) //8 stands for 8% but the function will treat this as 10%
//returns $slice = array ("I");
I didn't find any similar question here, hope this is not too complex.
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));
}
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