How to insert an element into an array[]?

Asked

Viewed 40 times

3

THIS EXAMPLE ONLY RETURNS ME THE FIRST ITEM;

   $parcelas = 2;
        $valor  = 1500;
        $date = '2019-12-23';
        $valor_parcela = $valor / $parcelas;
        $boletos = [];

        for (
            $i = 1;
            $i <= $parcelas;
            $i++
        ) {
            $date_sum_month = date('d/m/Y', strtotime("+{$i} month", strtotime($date)));
            $boletos += ["numero" => $i, "date" => $date_sum_month, "valor" => $valor_parcela];
        }


        return json_encode($boletos);
    }

RETURN

{
  "numero": 1,
  "date": "23/01/2020",
  "valor": 750
}

DESIRABLE RETURN

{
  "numero": 1,
  "date": "23/01/2020",
  "valor": 750
}

{
  "numero": 2,
  "date": "23/02/2020",
  "valor": 750
}
.
.
.
.

1 answer

7


If it is an array you should not concatenate other things into the array, you need to use a positional or push a new item, for example:

array_push($boletos, ["numero" => $i, "date" => $date_sum_month, "valor" => $valor_parcela]);

Reference: array_push

Browser other questions tagged

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