php - Split a number into 4 specified parts thats togetter the same number -



php - Split a number into 4 specified parts thats togetter the same number -

need split number illustration 5000 4 parts in array

$total = 5000;

array should like:

array ( [0] => 500 [1] => 250 [2] => 250 [3] => 4000 )

so if user enters 600 illustration need array this:

array ( [0] => 500 [1] => 100 [2] => 0 [3] => 0 )

this got, im sure there improve way. when come in 600 illustration 2 undefined offsets

$total_spidex = 5000; $price_total = array(); for($i=1; $i<=$total_spidex; $i++) { if($i <= 500) { $price_total[1][] = $i; } elseif($i >500 && $i <= 750) { $price_total[2][] = $i; } elseif($i >750 && $i <= 1000) { $price_total[3][] = $i; } elseif($i >1000) { $price_total[4][] = $i; } } $sum = 0; $sum = (count($price_total[1]) * 12) + (count($price_total[2]) * 11) + (count($price_total[3]) * 10) + (count($price_total[4]) * 9);

$number = 5000; // initial number $limit = 1000; // limit chunks $parts = array( array(500, 250, 250, 0), // dividers $number >= $limit, 0 - rest of # array(500, 250, 100, 0) // dividers $number < $limit ); $result = array(); // array results $blocks = $number < $limit; // set of dividers utilize foreach($parts[$blocks] $divider) if ($number > $divider && $divider > 0) { $result[] = $divider; // if number larger divider, add together divider $number -= $divider; // subtract divider number } else { $result[] = $number; // otherwise add together number $number = 0; // , set 0 } var_dump($result); // output result

no nested loops, conditions , can modify , add together more numerical values $parts array. if there no difference between parts above , below $limit, code more simple (may did not understand correctly comments)

$number = 500; $parts = array(500, 250, 250, 0); $result = array(); foreach($parts $divider) if ($number > $divider && $divider > 0) { $result[] = $divider; $number -= $divider; } else { $result[] = $number; $number = 0; } var_dump($result);

output asked for.

php

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -