Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a percentage of an array?

Tags:

arrays

php

slice

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.

like image 856
Giorgio Avatar asked Dec 17 '22 05:12

Giorgio


1 Answers

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));
}
like image 141
Tim Cooper Avatar answered Jan 03 '23 13:01

Tim Cooper