Ashburn, April 29, 2017

Split a number into smaller random number segments (chunks) in PHP

split-a-number-into-smaller-random-number-segments-chunks

Hi,

I needed to split a number into smaller random number segments in php. I needed this function to implement in a client project. I could not find it anywhere online. I am posting it here for if someone ever needs it.

It will take a number and return smaller numbers that add up to the former number. The function takes two arguments, the number to be segmented and the number of segments.

For example:

Number 10 with 4 segments could return an array with the following elements: “3,4,2,1” or “1,5,2,2”, etc

Number 20 with 5 segments could return an array with the following elements: “8,2,5,3,2” or “1,10,5,2,2”, etc.

I hope you find the function helpful.

Cheers!



function number_into_random_segments( $number, $segments ){
	
	$segments_sizes = false;
	
	if( $number >= $segments 
		and is_numeric( $number )   and $number > 0 
		and is_numeric( $segments ) and $segments > 0 ) :
	
		$segments_sizes = array();
		$number_avl   = $number;
		$segments_avl = $segments;

		for( $i = 1; $i <= $segments; $i++ ) :

			// if it is the last element
			if( $i == $segments ) :
				$segments_sizes[] = $number_avl;
			else :		

				$max_segment_size = $number_avl - $segments_avl + 1;
				$current_segment  = rand( 1, $max_segment_size );				
				$segments_sizes[] = $current_segment;		
				$number_avl  -= $current_segment;
				$segments_avl--;

			endif;

		endfor;	
		
	endif;	
	
	return $segments_sizes;
}


About Karlos Maldonado 36 Articles
Computer Sciences Engineer graduated from Florida Atlantic University (FAU) in Boca Raton, Florida. Has gotten great experience in the IT and Web Development industry working for companies such as SIRIUS XM RADIO, 4MEDIA as well as collaborating with local companies.

Be the first to comment

Leave a Reply

Your email address will not be published.