Create array through function

Asked

Viewed 94 times

0

Is there any way to return a array, something like:

$array = [
     "parcela" => "1",
     "valor"   => "100",
];

Using the function below? I need to return one array with the number of plots and the value.:

function calcParcelaJuros($valor_total,$parcelas,$juros=0){
   if($juros==0){
      $string = 'PARCELA - VALOR <br />';
      for($i=1;$i<($parcelas+1);$i++){
         $string .= $i.'x (Sem Juros) - R$ '.number_format($valor_total/$parcelas, 2, ",", ".").' <br />';
      }
      return $string;
   }else{
      $string = 'PARCELA - VALOR <br />';
      for($i=1;$i<($parcelas+1);$i++){
         $I =$juros/100.00;
         $valor_parcela = $valor_total*$I*pow((1+$I),$parcelas)/(pow((1+$I),$parcelas)-1);
         $string .= $i.'x (Juros de: '.$juros.'%) - R$ '.number_format($valor_parcela, 2, ",", ".").' <br />';
      }
      return $string;
   }
}



print(calcParcelaJuros(250,4,2));

?>

1 answer

1


Yes, you can return a filled array and then use this to display the information, for example

<?php

function calcParcelaJuros($valor_total, $parcelas, $juros = 0){
    $parcelado = [];

    if ($juros > 0) { // se for com juros, calculamos o valor contando com o juro
        $I = $juros/100.00;
        $valor = $valor_total * $I * pow((1 + $I), $parcelas) / (pow((1 + $I), $parcelas) - 1);
    } else { // senao é porque é sem juro
        $valor = $valor_total / $parcelas; 
    }

    // em vez de usar um ciclo, fazemos um array_fill, do indice 1 até ao numero de $parcelas e colocamos o valor
    $parcelado = array_fill(1, $parcelas, $valor);

    return $parcelado;
}

// presumo que ja tenhas as variaveis assim
$o_valor_total = 250;
$o_numero_de_parcelas = 4;
$o_valor_dos_juros = 2;

$parcelado = calcParcelaJuros($o_valor_total, $o_numero_de_parcelas, $o_valor_dos_juros);

foreach ($parcelado as $parcela => $valor) {
    $nota = ($o_valor_dos_juros > 0) ? "Juros de: {$o_valor_dos_juros}%" : "Sem Juros";
    $valor_formatado = number_format($valor, 2, ",", ".");

    echo "{$parcela}x ({$nota}) - R$ {$valor_formatado} <br />";
}

I prefer to create my functions having only 1 responsibility, being that the above example is only the function that makes the calculation of the plots, would have another to show the formatted result as intended (which above is the foreach).

Edit

To add the due date, you can do something like this, although, as the comment says, you could also do just one cycle to fill the array.

<?php

function calcParcelaJuros($valor_total, $parcelas, $data_primeiro_vencimento, $juros = 0){
    $parcelado = [];

    if ($juros > 0) { // se for com juros, calculamos o valor contando com o juro
        $I = $juros/100.00;
        $valor = $valor_total * $I * pow((1 + $I), $parcelas) / (pow((1 + $I), $parcelas) - 1);
    } else { // senao é porque é sem juro
        $valor = $valor_total / $parcelas; 
    }

    // em vez de usar um ciclo, fazemos um array_fill, do indice 1 até ao numero de $parcelas e colocamos o valor
    $parcelado = array_fill(1, $parcelas, ['valor' => $valor, 'juro' => $juros]);

    // adicionamos as datas entao depois, embora pudessemos fazer tudo no mesmo ciclo..
    foreach ($parcelado as $p => $parcela) {
        if (empty($data_vencimento)) {
            $data_vencimento = $data_primeiro_vencimento;
        } else {
            $data_vencimento = date_add($data_vencimento, date_interval_create_from_date_string('30 days'));
        }

        $parcelado[$p]['parcela'] = $p; // para manter o numero do pagamento
        $parcelado[$p]['data_vencimento'] = $data_vencimento->format('Y-m-d');
    }

    return $parcelado;
}

// presumo que ja tenhas as variaveis assim
$o_valor_total = 250;
$o_numero_de_parcelas = 4;
$data_primeiro_vencimento = date_create('2018-01-31');
$o_valor_dos_juros = 2;

$parcelado = calcParcelaJuros($o_valor_total, $o_numero_de_parcelas, $data_primeiro_vencimento, $o_valor_dos_juros);

foreach ($parcelado as $parcela) {
    extract($parcela); // usamos o extract para as chaves do array serem variaveis dentro deste foreach

    $nota = ($juro > 0) ? "Juros de: {$juro}%" : "Sem Juros";
    $valor_formatado = number_format($valor, 2, ",", ".");

    echo "{$parcela}x ({$nota}) - R$ {$valor_formatado} (Vence em {$data_vencimento})<br />";
}
  • Thanks for the return, actually I just need the value, no formatting even.

  • Using this same function, it is possible to bring the due dates every 30 days ? I know you are not in the question, but just to know

  • I tested, even created an array, but look how it turned out, https://imgur.com/OJcLTxa It is possible to leave as $array = [ "parcel" => "1", "value" => "100", ];

  • I removed the 2nd previous example and replaced it with one that includes the expiration date being extended every 30 days. You can also have 1 more parameter after or before the $juros to accept the time interval between each maturity.

  • perfect @milk, you can’t imagine how much it helped me. Thank you so much.

  • one more question, the array index, shouldn’t start with [0] ? , because it starts with [1] ?

  • the array_fill accepts as first parameter the first index to use, as is 1 the array starts with 1, although it could be 0 and the code later had this in mind

  • I will popular a table using Bootstrap table, all cases where the array has 0 as Index, it works, but in this case, which starts with 1, it has not populated. I don’t know if it can be that.. If it’s the case to start with 0, how can I do it?

  • Set the array_fill to start at 0, you may have to end the array_fill as $parcelas - 1, but you have to confirm, I’m on my phone now and I can’t. Later add a +1 to the line parcelado[$p]['parcela'] = $p;

  • I’m also on the phone, but I already try and get back here . Thanks for the readiness..

  • you don’t have to put the -1

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.