How to separate array in odd / even and calculate multiple number?

3

I'm doing a script to separate odd number and even number from a array entered via form option, and make specific calculation about them (to separate odd number from pair array am using explode and implode to put them all on the same line, but my code is incomplete.)

My question is: How to calculate so that in the final result the value is rounded up to a multiple of 10?

EXAMPLE: end result: 135

to be a multiple of 10, 5 is missing, total 140.

Code:

<?php
//separa os numeros da entrada da array retirando espaços vazios
$numUPC = explode(',', trim(trim($final_array), ',')); 
//final_array gerando erro undefined, motivo variavel sem entrada (Vazia)

$UPCdigito = array();
$numUPCpar = array();
$numUPCimpar = array();
$numArredondado = array();

//filtor de numero par e impar
foreach ($numUPC as $key => $value) {
    if ($key % 2 == 0) {
        $numUPCpar[] = $value;
    } else {
        $numUPCimpar[] = $value;
    }
}

$numUPCpar  = implode(', ', $numUPCpar);
$numUPCimpar = implode(', ', $numUPCimpar);

//calculo
$numUPCimpar = array_sum($numUPCimpar);
$numUPCpar = array_sum($numUPCpar);
$UPCdigito = $numUPCimpar * 3;
$UPCdigito = $UPCdigito + $numUPCpar;
$numArredondado = (round($UPCdigito / 10, 0) )* 0.5

?>

Is the logic of the odd and even number filter correct? And how do I identify in my final result how much is missing for the number to be a multiple of 10?

I tried to use round , but it's vague.

    
asked by anonymous 09.05.2015 / 07:53

2 answers

2

The odd or even check is correct. To round to multiples of 10 you can do this:

<?php
function round_multiple10_up($num) {
    $mod = $num % 10;

    if ($mod !== 0)
        return (10 - $mod) + $num;

    return $num;
}

function round_multiple10_down($num) {
    $mod = $num % 10;

    if ($mod !== 0)
        return $num - $mod;

    return $num;
}


$test = 144;

echo round_multiple10_up($test); //150
echo PHP_EOL;
echo round_multiple10_down($test); //140

You can try this code at this link: link

    
09.05.2015 / 13:59
0
/**
O array original com os números
*/
$arr = [11,22,31,41,53,67,71,89,90,106];

/**
Organiza os números ímpares e pares num array.
O termo "even" significa "par", o termo "odd" significa "ímpar".
*/
foreach ($arr as $v)
    $rs[(($v % 2 == 0)? 'even' : 'odd')][] = $v;

/**
Verifica se existe o índice de números pares e aplica a soma total e o arredondamento para um múltiplo de 10. O arredondamento é sempre para cima.
*/
if (isset($rs['even']))
    $rs['sum']['even'] = ceil(array_sum($rs['even']) / 10) * 10;

/**
Verifica se existe o índice de números ímpares e aplica a soma total e o arredondamento para um múltiplo de 10. O arredondamento é sempre para cima.
*/
if (isset($rs['odd']))
    $rs['sum']['odd'] = ceil(array_sum($rs['odd']) / 10) * 10;

/**
Imprime o resultado, para depuração.
*/
print_r($rs);
    
19.10.2015 / 07:17